Haskell中的const函数 [英] const function in Haskell
问题描述
函数 const
在Prelude中定义为:
const x_ = x
在GHCi中,当我试过的时候
Prelude> const 6 5 - >给出6
但是当我尝试时
前奏> const id 6 5 - >给出5
即使进行了如
前奏> (常数id 6)5 - >给出5
这个函数不应该给 6
作为函数 id
的输出具有类型 id :: a - >一个
应该像
Prelude> (常数6)5 - >为什么函数 const
的行为有所不同?解决方案您似乎认为这相当于 const(id 6)5 ,其中 id 6
的计算结果为6,但事实并非如此。没有这些圆括号,你将 id
函数作为第一个参数传递给 const
。再看看 const
的定义:
const x _ = x
这意味着常量id 6 = id
。因此, const id 6 5
相当于 id 5
,这确实是5。
The function const
is defined in Prelude as:
const x _ = x
In GHCi, when I tried
Prelude> const 6 5 -> Gives 6
But when I tried
Prelude> const id 6 5 -> Gives 5
Even after making changes like
Prelude> (const id 6) 5 -> Gives 5
Shouldn't this function give 6
as the output of function id
has type id :: a -> a
which should bind like
Prelude> (const 6) 5 -> Gives 6
Why does function const
behave differently?
解决方案 You seem to be thinking that this is equivalent to const (id 6) 5
, where id 6
evaluates to 6, but it isn't. Without those parentheses, you're passing the id
function as the first argument to const
. So look at the definition of const
again:
const x _ = x
This means that const id 6 = id
. Therefore, const id 6 5
is equivalent to id 5
, which is indeed 5.
这篇关于Haskell中的const函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!