gpt4 book ai didi

haskell - 这个haskell函数中的这些值来自哪里?

转载 作者:行者123 更新时间:2023-12-01 07:23:04 25 4
gpt4 key购买 nike

假设我有以下功能:

sumAll :: [(Int,Int)] -> Int
sumAll xs = foldr (+) 0 (map f xs)
where f (x,y) = x+y
sumAll [(1,1),(2,2),(3,3)]的结果将是 12 .

我不明白的是 (x,y)在哪里值来自。好吧,我知道它们来自 xs变量,但我不明白如何。我的意思是,在没有 where 关键字的情况下直接执行上面的代码,它会是这样的:
sumAll xs = foldr (+) 0 (map (\(x,y) -> x+y) xs)

我无法理解,在最上面的代码中, f 是怎么做的?变量和 (x,y)变量代表 (\(x,y) -> x+y) lambda 表达式。

最佳答案

希望这会有所帮助。关键是f应用于列表的元素,它们是成对的。

sumAll [(1,1),(2,2),(3,3)] 
-- definition of sumAll
= foldr (+) 0 (map f [(1,1),(2,2),(3,3)])
-- application of map
= foldr (+) 0 (f (1,1) : map f [(2,2),(3,3)])
-- application of foldr
= 0 + foldr (+) (f (1,1)) (map f [(2,2),(3,3)])
-- application of map
= 0 + foldr (+) (f (1,1)) (f (2,2) : map f [(3,3)])
-- application of foldr
= 0 + (f (1,1) + foldr (+) (f (2,2)) (map f [(3,3)]))
-- application of f
= 0 + (2 + foldr (+) (f (2,2)) (map f [(3,3)]))
-- application of map
= 0 + (2 + foldr (+) (f (2,2)) (f (3,3) : map f []))
-- application of foldr
= 0 + (2 + (f (2,2) + foldr (+) (f (3,3)) (map f [])))
-- application of f
= 0 + (2 + (4 + foldr (+) (f (3,3)) (map f [])))
-- application of map
= 0 + (2 + (4 + foldr (+) (f (3,3)) []))
-- application of foldr
= 0 + (2 + (4 + f (3,3)))
-- application of f
= 0 + (2 + (4 + 6))
= 0 + (2 + 10)
= 0 + 12
= 12

关于haskell - 这个haskell函数中的这些值来自哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/376959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com