如何在haskell中实现嵌套函数

时间:2014-11-20 02:12:36

标签: haskell

I recently came across this question:

其中主要询问如何实现此函数来计算f(n)的极限:

enter image description here

我如何在haskell中实现它?我正在努力学习函数式编程,这对我来说似乎是一个很好的挑战

1 个答案:

答案 0 :(得分:10)

有很多方法!

这里使用递归辅助函数:

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))

手工解决:

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)))

这是使用递归辅助函数执行此操作的另一种方法:

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)

手工解决:

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)))

第一种方法是尾递归,而第二种方法只是递归。

或者,如链接所示,通过折叠

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

再次,手工解决:

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)