Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Maybe type in Haskell

Tags:

haskell

maybe

I'm trying to utilize the Maybe type in Haskell. I have a lookup for key, value tuples that returns a Maybe. How do I access the data that was wrapped by Maybe? For example I want to add the integer contained by Maybe with another integer.

like image 509
dpsthree Avatar asked Sep 04 '10 16:09

dpsthree


People also ask

What are maybe types?

It's common for JavaScript code to introduce “optional” values so that you have the option of leaving out the value or passing null instead. Using Flow you can use Maybe types for these values. Maybe types work with any other type by simply prefixing it with a question mark ?

Is maybe a Monad?

In FP we often loosely say things like "arrays are monads" or "maybe values are monadic" etc. However, speaking more strictly, it is not the values (like [1, 2, 3] , Nothing , or Just(6) ) that are monads, but the context (the Array or Maybe "namespace" as you put it).


2 Answers

Alternatively you can pattern match:

case maybeValue of   Just value -> ...   Nothing    -> ... 
like image 122
Martijn Avatar answered Oct 16 '22 14:10

Martijn


You could use Data.Maybe.fromMaybe, which takes a Maybe a and a value to use if it is Nothing. You could use the unsafe Data.Maybe.fromJust, which will just crash if the value is Nothing. You likely want to keep things in Maybe. If you wanted to add an integer in a Maybe, you could do something like

f x = (+x) <$> Just 4 

which is the same as

f x = fmap (+x) (Just 4) 

f 3 will then be Just 7. (You can continue to chain additional computations in this manner.)

like image 39
arsenm Avatar answered Oct 16 '22 15:10

arsenm