[Haskell-beginners] Re: = vs <-

Ertugrul Soeylemez es at ertes.de
Wed Aug 11 16:35:56 EDT 2010


prad <prad at towardsfreedom.com> wrote:

> i'm using them right i think because it works, but my understanding is
> fuzzy.
>
> it seems <- is used when you do things like load a file or get
> arguments from outside or if you are return something from a function
>
> these seem to take the form of something other than an internal type
> like Int or String and have to be 'massaged' into use with things like
> show or fromSql etc
>
> the = is used with let and seems to work for any assignments that are
> internal.
>
> are these assessments correct?

No.  You are mixing up monadic computations with normal Haskell
functions.  First of all using "=" you make an equation.  You are not
saving a result, you are just saying that two things are the same.  You
use this to define values and functions:

  (age, sex, location) = (25, Male, "Germany")

  fourthRoot = sqrt . sqrt

You could just as well write '25' whereever your write 'age'.  And you
could just as well write 'sqrt . sqrt' whereever you write 'fourthRoot',
because you defined them to be the same thing.

The '<-' syntax on the other hand is unrelated to functions.  You use it
to give the result of a monadic computation a name.  Example:

  line <- getLine

getLine is a value of type IO String.  Notice that getLine is /not/ a
function.  It's simply a value.  But it's a monadic one, because IO is a
monad, so whenever you use 'do' notation, you can refer to the result of
it by using the '<-' syntax.

Let's go deeper into it:

  content <- readFile "blah.txt"

Now readFile is a function.  It's of the following type:

  readFile :: FilePath -> IO String

Because it is a function you need to apply it to a value of type
FilePath first, yielding, guess what, a simple value.  That value is of
type IO String, so it's a monadic value, an IO computation.  That
computation, when run, has a result.  And by using '<-' you give this
result the name 'content', so you can refer to it.

Again, 'content' is /not/ the result of the readFile function, because
that result is a computation of type IO String.  Let's see the
difference:

  let readBlahTxt = readFile "blah.txt"
  content <- readBlahTxt

This should show the difference more clearly.


Greets,
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/




More information about the Beginners mailing list