Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement nested functions in haskell

Tags:

haskell

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

like image 914
Krimson Avatar asked Nov 20 '14 02:11

Krimson


1 Answers

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)
like image 97
rampion Avatar answered Nov 15 '22 08:11

rampion