Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

const function in Haskell

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...