我最近在Haskell遇到了这个奇怪的问题.下面的代码应该返回一个修剪到一个范围的值(如果它在high它之上它应该返回,high如果它在low它下面应该返回low.
inRange :: Int -> Int -> Int -> Int
inRange low high = max low $ min high
Run Code Online (Sandbox Code Playgroud)
错误消息是:
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
Run Code Online (Sandbox Code Playgroud)
难道不应该采取另一种说法并将其置于高位吗?我已经尝试过其他可能性:
\x -> max low $ min high x
Run Code Online (Sandbox Code Playgroud)
和
\x -> max low $ (min high x)
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
Thr*_*eFx 12
($) 定义为:
f $ x = f x
Run Code Online (Sandbox Code Playgroud)
所以你的例子实际上是:
max low (min high)
Run Code Online (Sandbox Code Playgroud)
这是错的,因为你真的想要
max low (min high x)
Run Code Online (Sandbox Code Playgroud)
使用函数组合,定义为:
f . g = \x -> f (g x)
Run Code Online (Sandbox Code Playgroud)
以及\x -> max low (min high x)我们得到的工作示例:
\x -> max low (min high x)
== max low . min high -- by definition of (.)
Run Code Online (Sandbox Code Playgroud)