6

I recently came across this question:

Which basically asks how to implement this function to calculate the limit of f(n):

enter image description here

How would I implement this in haskell? I am trying to learn functional programming and this seems a good challenge for me now

1 Answer 1

11

There's a bunch of ways!

Here's one using a recursive helper function:

f :: (Eq a, Floating a) => a -> a
f n = f' n n
  where f' 1 x = x
        f' n x = let n' = n-1 in f' n' (n' / (1 + x))

Working it out by hand:

f 1 = f' 1 1 
    = 1
f 2 = f' 2 2 
    = f' 1 (1 / (1 + 2)) 
    = 1/(1+2)
f 3 = f' 3 3 
    = f' 2 (2 / (1 + 3))
    = f' 1 (1 / (1 + (2 / (1 + 3))))
    = 1 / (1 + (2 / (1 + 3)))

Here's a different way to do it with a recursive helper function:

f :: (Eq a, Floating a) => a -> a
f n = f' 1 n
  where f' a n | a == n    = a
               | otherwise = a / (1 + f' (a+1) n)

Working it out by hand:

f 1 = f' 1 1 
    = 1
f 2 = f' 1 2 
    = 1 / (1 + f' 2 2) 
    = 1 / (1 + 2)
f 3 = f' 1 3 
    = 1 / (1 + f' 2 3)
    = 1 / (1 + (2 / (1 + f' 3 3)))
    = 1 / (1 + (2 / (1 + 3)))

The first approach was tail-recursive while the second was simply recursive.

Or, as the link says, by a fold

f :: (Eq a, Floating a) => a -> a
f n = foldr1 (\n x -> n / (1 + x)) [1..n]

Again, working it out by hand:

f 5 = foldr1 (\n x -> n / (1 + x)) [1,2,3,4,5]
    = g 1 (g 2 (g 3 (g 4 5)))
    = g 1 (g 2 (g 3 (4 / (1 + 5))))
    = g 1 (g 2 (3 / (1 + (4 / (1 + 5)))))
    = g 1 (2 / ( 1 + (3 / (1 + (4 / (1 + 5))))))
    = 1 / (1 + (2 / ( 1 + (3 / (1 + (4 / (1 + 5)))))))
  where g = \n x -> n / (1 + x)
Sign up to request clarification or add additional context in comments.

2 Comments

ap is exported from Control.Monad, so I'd avoid using that name.
Thanks for your answer. Will take me a while to understand how it works but thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.