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
538 views
in Technique[技术] by (71.8m points)

io - What is the default type evaluation of MonadPlus in Haskell?

I have the following code:

import Control.Monad

coin :: MonadPlus m => m Int
coin = return 0 `mplus` return 1

If I evaluate coin :: Maybe Int on the interpreter, it prits Just 0. That's normal because of the implementation of Maybe as instance of MonadPlus.

If I evaluate coin :: [Int]on the interpreter, it prints [0, 1], because the implementation of mplus on list is an append.

But if I evaluate coin, without any type decorators, it prints 0. Why? What type does the interpreter 'converts' coin to evaluate it?

This code is extracted from: http://homes.sice.indiana.edu/ccshan/rational/S0956796811000189a.pdf

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yeah, this is a not super-well documented corner of ghci. When you enter an expression into ghci, it uses the expression's type to decide what to do:

  1. IO (): Run the action, do nothing further.
  2. Show a => IO a: Run the action and print the result.
  3. any other IO a: Run the action, do nothing further.
  4. anything else: wrap the whole expression with print.

How does it decide which of these types a thing has? Easy: it tries to unify the type of your expression which each of the above signatures in turn and solve all resulting constraints. (For the cognoscenti: this is in addition to the extended defaulting rules! This explains why it appears to be defaulting the m, even though neither the standard defaulting rules nor the extended defaulting rules say what default to use.)

So, since your expression does not unify with IO () but does unify with Show a => IO a, ghci finds m ~ IO (and a ~ Int) during unification, discovers that there is a MonadPlus IO (and a Show Int) instance to resolve the constraints, runs your action, and prints the result.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...