[Haskell-beginners] help using Data.Map lookup - how to get values after the "Just" constructor

Daniel Fischer daniel.is.fischer at web.de
Tue Sep 21 10:58:12 EDT 2010


On Tuesday 21 September 2010 15:37:35, Martin Tomko wrote:
> Hi edgar,
> the whole of my code and the input data are one contained world, I am
> not using mondas - as I don't understand them properly,

Understanding will improve if you start to use them (don't go in too deep 
too fast, just start tinkering a little with Monads in Maybe and [], take a 
look at Control.Monad.State, build up experience and understanding).

> and they seem
> not to be necessary for the simple algebra I am trying to develop. Do I
> really need to use them here?

Not really. Monads make many things more convenient, but you can do almost 
all without them.
In the case at hand, using Maybe's Monad instance could add some 
convenience and elegance, but it'd not make a huge difference.

>
> Now, to your example:
>  >>>Try for example in ghci: fromJust $ Just 1 >>= (\x -> return $ x +
> 1) (I also had to search for definition of the $ operator, totally
> avoided in the two books I have, and seems to be just syntactic sugar
> instead of parentheses. Argh.)

Apart from avoiding parentheses, ($) has a few other uses, it can be passed 
to some higher order functions and it's nice to use for sections,

map ($ 4) [sin, cos, (^2)]

zipWith ($) [sin, cos, (^2)] [1,2,3]

In both cases, ($) could be replaced with id, since

($) :: (a -> b) -> a -> b
f $ x = f x

, ($) *is* the identity function, restricted to function types and with a 
different fixity, but somehow map ($ 4) looks less intriguing than
map (`id` 4), doesn't it?

>
> this seems to be equivalent to fromJust (Just 1),

It's fromJust (Just 2).

foo :: Int -> Maybe Int
foo x = Just (x+1)

The function (\x -> return $ x+1) is just foo, only more general (works for 
any Num type and any Monad).

Just val >>= func = func val, so
Just 1 >>= foo = foo 1 = Just (1+1) = Just 2

Nothing >>= _ = Nothing

> where I would assuem a
> result of 1. But the example seems to be dependent on whatever x is
> entered by keyboard. Am I right?

No, the x is (bound to) the argument of Just on the left of the (>>=), in 
this case 1.

Keyboard input lives in the IO Monad, there's no such stuff available in 
the Maybe Monad.

In

getLine >>= \line -> putStrLn (reverse line)

the name line is bound to the keyboard input.

Just "A line" >>= \line -> putStrLn (reverse line)

doesn't type-check, because the Monad to the left of (>>=) is different 
from the Monad on the right (left: Maybe, right: IO).

>
> Cheers
> Martin



More information about the Beginners mailing list