Haskell 将 Int 与 Int -> Int 混淆
Haskell confuses Int with Int -> Int
我最近在 Haskell 中遇到了这个奇怪的问题。下面的代码应该 return 一个值被修剪到一个范围内(如果它高于 high
它应该 return high
如果它低于 low
它应该 return 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
是不是应该再取一个参数,放到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
($)
定义为:
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 (.)
我最近在 Haskell 中遇到了这个奇怪的问题。下面的代码应该 return 一个值被修剪到一个范围内(如果它高于 high
它应该 return high
如果它低于 low
它应该 return 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
是不是应该再取一个参数,放到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
($)
定义为:
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 (.)