哈斯克尔表达评估

时间:2015-05-11 18:09:36

标签: haskell evaluation

我是haskell的新手,我希望您就以下haskell表达式评估向我提出建议。

f xs = foldr (\x n->n+1) 0 xs

功能

f [1, 4]

评价

(\x n->n+1) 1 (foldr  (\x n->n+1) 0 [4])
= (foldr  (\x n->n+1) 0 [4]) + 1
= ((\x n->n+1) 4 (foldr  (\x n->n+1) 0 [4])) + 1
= (foldr  (\x n->n+1) 0 [] + 1) + 1
= (0 + 1) + 1 
= 1 + 1
= 2

1 个答案:

答案 0 :(得分:2)

首先,我们需要实现foldr:

foldr f z []     = z 
foldr f z (x:xs) = f x (foldr f z xs)

现在让我们尝试追踪"我们的计算f [1, 4]

f [1, 4]  -- rewrite list 
f (1:(4:[]))  -- replace f function where xs = (1:(4:[]))
foldr (\x n-> (+) n 1 ) 0 (1:(4:[])) 

-- using foldr f z (x:xs) = f x (foldr f z xs)
-- where f = (\x n -> (+) n 1), z = 0, x = 1, xs = (4:[])
(\x n ->(+) n 1) 1 ( foldr (\x n -> (+) n 1) 0 (4:[]))

-- lambda function will be evaluated with x = 1, n = ( foldr (\x n -> n+1) 0 (4:[]))
(+) (foldr (\x n -> n+1) 0 (4:[])) 1

-- (+) will try to evaluate first parameter
-- foldr will be applied with f = (\x n -> (+) n 1), z = 0,  x = 4, xs = []
(+) ((\x n -> (+) n 1) 4 (foldr (\x n -> (+) n 1) 0 [] )) 1

-- now again the lambda will be evaluated where x = 4 and n = (foldr (\x n -> (+) n 1) 0 [] )

(+) ( (+) (foldr (\x n -> (+) n 1) 0 [] ) 1 ) 1

--  now foldr will be evaluated again but this time first form will be used, so just z counts: f = (\x n -> (+) n 1), z = 0, [] = []
(+) ( (+) ( 0 ) 1 ) 1

-- now just go with the flow
(+) ( (+) 0 1 ) 1
(+) ( 1 ) 1
(+) 1 1
2