让我们说我有以下功能:

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变量,但我不明白如何。我的意思是,这样做上面的代码的情况下直接在其中关键字,这将是这样的:

sumAll xs = foldr (+) 0 (map (\(x,y) -> x+y) xs)

和我无法理解,在顶部代码,请问f变量和变量(x,y)表示(\(x,y) -> x+y) lambda表达式。

有帮助吗?

解决方案

在Haskell中,函数是第一类的数据类型。

这意味着可以通过周围的功能类似于其它类型的数据,如整数和字符串。

在您的代码以上声明“F”是一个函数,该函数在一个argumenta(两个值(X,Y)的元组),并返回(X + Y)。

的结果

foldr相似是另一种函数,它接受在3个参数,一个二进制函数(在这种情况下+)起始值(0)和值的阵列,以在迭代器

在短 '其中f(X,Y)= X + Y' 只是作用域简写

sumAll :: [(Int,Int)] -> Int
sumAll xs = foldr (+) 0 (map myFunctionF xs)

myFunctionF :: (Int,Int) -> Int
myFunctionF (x,y) = x + y

修改:如果您不确定foldr相似是如何工作的,检查出的 Haskell的参考Zvon的 下面是与foldl /地图的示例性实现。

foldl :: (a -> b -> b) -> b -> [a] -> b
foldl _ x [] = x
foldl fx (y:ys) = foldl f (f y x) ys

map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = (f x) : (map f xs)

其他提示

希望这将有助于。关键是,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

不是一个答案,但我想我应该指出的是,你的函数f:

f (x, y) = x + y

可以表示为

f = uncurry (+)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top