我试图用foldr
来定义原始递归,如A tutorial on the universality and expressiveness on fold第4.1章中所述。
这是第一次尝试
simpleRecursive f v xs = fst $ foldr g (v,[]) xs
where
g x (acc, xs) = (f x xs acc,x:xs)
但是,上述定义不会停止head $ simpleRecursive (\x xs acc -> x:xs) [] [1..]
以下是停止
的定义simpleRecursive f v xs = fst $ foldr g (v,[]) xs
where
g x r = let (acc,xs) = r
in (f x xs acc,x:xs)
鉴于定义几乎相似但结果不同,为什么会有所不同?它与Haskell模式如何匹配有关吗?
答案 0 :(得分:3)
这两个函数之间的关键区别在于
g x r = let (acc, xs) = r
in (f x xs acc, x:xs)
元组构造函数上的模式匹配是无可辩驳的,而在
中g x (acc, xs) = (f x xs acc, x:xs)
不是。换句话说,g
的第一个定义等同于
g x ~(acc, xs) = (f x xs acc, x:xs)