Haskell将Int与Int混淆 - >诠释

时间:2017-03-19 15:57:09

标签: haskell ghc ghci

我最近在Haskell遇到了这个奇怪的问题。以下代码应该返回一个范围缩小的值(如果它在high之上,它应该返回high如果它在low下面它应该返回low

inRange :: Int -> Int -> Int -> Int
inRange low high = max low $ min high

错误信息是:

scratch.hs:2:20:
    Couldn't match expected type ‘Int -> Int’ with actual type ‘Int’
    In the expression: max low $ min high
    In an equation for ‘inRange’: inRange low high = max low $ min high

scratch.hs:2:30:
    Couldn't match expected type ‘Int’ with actual type ‘Int -> Int’
    Probable cause: ‘min’ is applied to too few arguments
    In the second argument of ‘($)’, namely ‘min high’
    In the expression: max low $ min high

不应该采取另一种说法并将其置于高位吗?我已经尝试过其他可能性:

\x -> max low $ min high x

\x -> max low $ (min high x)

在GHCI中尝试时,我收到以下错误:

<interactive>:7:5:
    Non type-variable argument in the constraint: Num (a -> a)
    (Use FlexibleContexts to permit this)
    When checking that ‘inRange’ has the inferred type
      inRange :: forall a.
                 (Num a, Num (a -> a), Ord a, Ord (a -> a)) =>
                 a -> a

1 个答案:

答案 0 :(得分:12)

($)定义为:

f $ x = f x

所以你的例子实际上是:

max low (min high)

这是错误的,因为你真的想要

max low (min high x)

使用函数组合,定义为:

f . g = \x -> f (g x)

以及您的工作示例\x -> max low (min high x)

\x -> max low (min high x)
== max low . min high -- by definition of (.)