gpt4 book ai didi

Haskell 将 Int 与 Int 混淆 -> Int

转载 作者:行者123 更新时间:2023-12-01 07:34:50 25 4
gpt4 key购买 nike

我最近在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com