How to implement nested functions in haskell

I recently came across this question:

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

enter image description here

How would this be implemented in haskell? I am trying to learn functional programming, and now this seems like a good challenge to me.

+5
source share
1 answer

There are a lot of ways!

The recursive helper function is used here:

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

Manually working with it:

 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 another way to do this with a recursive helper function:

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

Manually working with it:

 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 , and the second was just recursive.

Or, as the link says, in a word

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

Again, working manually:

 f 5 = foldr1 (\nx -> 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 = \nx -> n / (1 + x) 
+10
source

Source: https://habr.com/ru/post/1207269/


All Articles