Here's another way to write diff(n) that computes in linear space and time. Another important distinction is the result is computed in a single n-sized loop instead of multiple loops
diff(n)
n
sq : Int -> Int sq n = n * n diff : Int -> Int diff n = let loop sum squares n = if n == 0 then sq sum - squares else loop (sum + n) (squares + sq n) (n - 1) in loop 0 0 n diff 10 == 2640
You could also implement loop generically using a union type and then implement diff with loop
loop
diff
type Loop state result = Recur state | Done result loop : state -> (state -> Loop state result) -> result loop init f = case (f init) of Recur state -> loop state f Done value -> value diff : Int -> Int diff n = loop ( 0, 0, n ) <| \( sum, squares, n ) -> if n == 0 then Done (sq sum - squares) else Recur ( sum + n, squares + sq n, n - 1 ) diff 10 == 2640
Both implementations are tail recursive and do not grow the stack
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here's another way to write
diff(n)
that computes in linear space and time. Another important distinction is the result is computed in a singlen
-sized loop instead of multiple loopsYou could also implement
loop
generically using a union type and then implementdiff
withloop
Both implementations are tail recursive and do not grow the stack