模式匹配与解构的严格性

时间:2016-08-26 06:39:50

标签: haskell recursion pattern-matching lazy-evaluation fold

我试图用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模式如何匹配有关吗?

1 个答案:

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