繁体   English   中英

对haskell中的复合函数感到困惑

[英]confused about composite function in haskell

let f = show.sum.map read.words
f "1 2"

这行得通。

show.sum.map read.words "1 2"

我收到错误消息:

<interactive>:19:19:
    Couldn't match expected type ‘a -> [String]’
                with actual type ‘[String]’
    Relevant bindings include
      it :: a -> String (bound at <interactive>:19:1)
    Possible cause: ‘words’ is applied to too many arguments
    In the second argument of ‘(.)’, namely ‘words "1 2"’
    In the second argument of ‘(.)’, namely ‘map read . words "1 2"’
Prelude> :t show.sum.map
show.sum.map
  :: (Num [b], Show b, Foldable ((->) [a])) => (a -> b) -> String
Prelude> show.sum.map read.words "1 2"

    <interactive>:21:19:
        Couldn't match expected type ‘a -> [String]’
                    with actual type ‘[String]’
        Relevant bindings include
          it :: a -> String (bound at <interactive>:21:1)
        Possible cause: ‘words’ is applied to too many arguments
        In the second argument of ‘(.)’, namely ‘words "1 2"’
        In the second argument of ‘(.)’, namely ‘map read . words "1 2"’
    Prelude> 

我想知道为什么吗? (show.sum.map读单词)“ 1 2”也可以工作。

问题在于,应用程序的绑定比实际上在所有Haskell运算符中具有最高优先级的应用程序更紧密。 这意味着您的代码实际上是解析

 show.sum.map read.(words "1 2")

之所以不进行检查,是因为words "1 2"的类型为String而不是可以用组成的类型. 为了解决这个问题,您可以使用$运算符,该运算符专门设计为充当应用程序,但是优先级最低,而不是最高。

 show.sum.map read.words $ "1 2"

将按预期工作,因为它具有正确的关联。 这就是为什么您会在Haskell代码(至少我的Haskell代码)中看到foo . bar . baz $ quux foo . bar . baz $ quux foo . bar . baz $ quux非常频繁。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM