[Haskell-beginners] Re: computation vs function
Ertugrul Soeylemez
es at ertes.de
Wed Apr 22 19:10:28 EDT 2009
Daniel Carrera <daniel.carrera at theingots.org> wrote:
> I have finished the tutorial at http://ertes.de/articles/monads.html
> and my understanding of monads has increased greatly. I still need to
> cement some concepts in my mind. What exactly is the difference
> between a computation and a function? Monads revolve around
> computations, so I'd like to understand computations better.
What I refer to as a 'computation' in the article is actually just a
value of type 'Monad m => m a'. I have chosen that term, because you
can apply it to any monad I've seen. As mentioned in section 5, you can
think of 'Just 3' as being a computation, which results in 3. But it's
important that this is not a function, but just an independent value.
You can think of a function of type 'a -> b' as a parametric value -- a
value of type 'b' depending on some value of type 'a'. That makes a
function of type 'Monad m => a -> m b' a parametric computation. A
computation, where something is missing, like with an open slot, where
you need to plug a cable in first.
By the way, this is where (>>=) comes into play. If you have a
computation, which needs a value, but that value comes as the result of
another computation, you can use the binding operator.
f :: Monad m => a -> m b
The 'f' function is a parametric computation of type 'm b', which
depends on a value of type 'a'. Now if
c :: Monad m => m a
and 'm' and 'a' in 'f' are the same as 'm' and 'a' in 'c', then
c >>= f
takes 'c', puts its result (of type 'a') into 'f', resulting in a
computation of type 'm b'.
Example: You have a computation 'myComp', which outputs a string to
stdout prefixed with "+++ ":
myComp :: String -> IO ()
myComp str = putStrLn ("+++ " ++ str)
If that string is available directly, just pass it to 'myComp', which
results in a computation. If that string is not available directly, but
comes as the result of another computation 'getLine', you use (>>=):
getLine >>= myComp
Greets,
Ertugrul.
--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://blog.ertes.de/
More information about the Beginners
mailing list