首页 文章

为什么(-2)与Haskell中的(\ x - > x - 2)不同? [重复]

提问于
浏览
1

这个问题在这里已有答案:

我正在学习使用CIS194(spring13)的Haskell . 今天当我试图处理作业4练习1时,我得到了一个错误

fun1' :: [Integer] -> Integer
fun1' = foldl' (*) 1 . map (-2) . filter even

据说:

error:
    ? No instance for (Num (Integer -> Integer))
        arising from a use of syntactic negation
        (maybe you haven't applied a function to enough arguments?)
    ? In the first argument of map, namely (- 2)
      In the first argument of (.), namely map (- 2)
      In the second argument of (.), namely map (- 2) . filter even
   |
12 | fun1' = foldl' (*) 1 . map (- 2) . filter even

   |                             ^^^

并且可以用 (\x -> x - 2) 替换 (-2) . 我认为它就像 filter (==0)map (*3) xs(-2) 应该是一个带有类型签名 Integer -> Integer 的函数,并且与 (\x -> x - 2) 具有相同的效果 .

所以我的问题是为什么他们不同?

1 回答

  • 9

    Haskell在 - 的语法中有一个特例;只要解析,它就被视为一元运算符,与 negate 同义 . 在编写语言时,人们认为负数通常比减法部分更需要(今天看来仍然如此) .

    然而,众所周知,人们偶尔会想要你做的事情,所以做出了规定: Prelude 包含一个名为 subtract 的函数,它只是将参数翻转到 (-) .

    > map (subtract 2) [1,2,3]
    [-1,0,1]
    

相关问题