haskell(ghci)中的点自由编程风格

时间:2015-03-17 13:44:01

标签: haskell pointfree

我在haskell中遇到了一组计算组合代码,我想我会在ghci中使用它来理解它是如何工作的。在ghci中,当我运行我感兴趣的代码时,它会失败,如下所示。

Prelude Data.List> filter ((== 2) . length) . subsequences [1,2,3]

<interactive>:19:1:
    No instance for (Show ([a0] -> [[a0]]))
      arising from a use of ‘print’
    In a stmt of an interactive GHCi command: print it
Prelude Data.List> filter ((== 2) . length) . subsequences [1,2,3]

<interactive>:20:28:
    Couldn't match expected type ‘a -> [[a1]]’
                with actual type ‘[[a0]]’
    Relevant bindings include
      it :: a -> [[a1]] (bound at <interactive>:20:1)
    Possible cause: ‘subsequences’ is applied to too many arguments
    In the second argument of ‘(.)’, namely ‘subsequences [1, 2, 3]’
    In the expression:
      filter ((== 2) . length) . subsequences [1, 2, 3]

我知道它必须是因为组合(点)运算符。在ghci中我必须将其更改为使用“$”符号来运行该代码,如下所示

Prelude Data.List> filter ((== 2) . length) $ subsequences [1,2,3]
[[1,2],[1,3],[2,3]]

当你用这种编程风格(无点)编写代码时,有人可以解释一下内部发生了什么吗?为什么当我直接使用该表达式时ghci失败了?

1 个答案:

答案 0 :(得分:9)

这只是运营商优先权的问题。您的代码正在被视为

(filter ((== 2) . length))    .     (subsequences [1,2,3])

然后GHCi抱怨subsequences [1,2,3]不是一个函数。所以,你需要括号:

(filter ((== 2) . length) . subsequences) [1,2,3]

$

filter ((== 2) . length) . subsequences $ [1,2,3]