Haskell 将 Int 与 Int 混淆 -> Int

标签 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

最佳答案

($)定义为:

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 将 Int 与 Int 混淆 -> Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42888723/

相关文章:

haskell - 这个 ghci session 中的类型是怎么回事?

python - Haskell、Python 和 Ruby 中的列表理解

performance - 减少 Haskell 程序中的垃圾收集暂停时间

haskell - 在沙箱中安装了 parsec,但在 ghci 中尝试加载文件时找不到库

haskell - 确定加载目标的 ModuleName

haskell - ghci 中的持久控制台历史记录

generics - 当我在 Haskell 中编写 "show"和 "read"时发生了什么?

haskell - 如何在 Haskell Control.Parallel.Strategies 中制定策略?

Haskell:[IO ()] 到 IO ()

haskell - 理解 Data.List 的 or & 和 w/Empty List