Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of a Maybe in Haskell

I'm relatively new to Haskell and began to read "Real World Haskell".

I Just stumbled over the type Maybe and have a question about how to receive the actual value from a Just 1 for example.

I have written the following code:

combine a b c = (eliminate a, eliminate b, eliminate c)                 where eliminate (Just a) = a                       eliminate Nothing = 0 

This works fine if I use:

combine (Just 1) Nothing (Just 2) 

But if I change, for example, 1 to a String it doesn't work.

I think I know why: because eliminate has to give back one type, which is, in this case, an Int. But how can I change eliminate to deal at least with Strings (or maybe with all kind of types)?

like image 351
Moe Avatar asked Feb 09 '11 01:02

Moe


People also ask

What does maybe mean in Haskell?

The Maybe type encapsulates an optional value. A value of type Maybe a either contains a value of type a (represented as Just a ), or it is empty (represented as Nothing ). Using Maybe is a good way to deal with errors or exceptional cases without resorting to drastic measures such as error .

What does <$> mean in Haskell?

It's merely an infix synonym for fmap , so you can write e.g. Prelude> (*2) <$> [1.. 3] [2,4,6] Prelude> show <$> Just 11 Just "11" Like most infix functions, it is not built-in syntax, just a function definition. But functors are such a fundamental tool that <$> is found pretty much everywhere.

What does Just do in Haskell?

It represents "computations that could fail to return a value". Just like with the fmap example, this lets you do a whole bunch of computations without having to explicitly check for errors after each step.


1 Answers

From the standard Prelude,

maybe :: b -> (a -> b) -> Maybe a -> b maybe n _ Nothing = n maybe _ f (Just x) = f x 

Given a default value, and a function, apply the function to the value in the Maybe or return the default value.

Your eliminate could be written maybe 0 id, e.g. apply the identity function, or return 0.

From the standard Data.Maybe,

fromJust :: Maybe a -> a fromJust Nothing = error "Maybe.fromJust: Nothing" fromJust (Just x) = x 

This is a partial function (does not return a value for every input, as opposed to a total function, which does), but extracts the value when possible.

like image 78
ephemient Avatar answered Oct 07 '22 21:10

ephemient