[Haskell-cafe] Getting the x out

michael rice nowgate at yahoo.com
Tue Apr 21 21:51:12 EDT 2009


There's a lot of well thought out stuff in Haskell, but getting familiar with it all seems like a huge task.

Thanks for the help.

Michael


--- On Tue, 4/21/09, Ross Mellgren <rmm-haskell at z.odi.ac> wrote:

From: Ross Mellgren <rmm-haskell at z.odi.ac>
Subject: Re: [Haskell-cafe] Getting the x out
To: "michael rice" <nowgate at yahoo.com>
Cc: haskell-cafe at haskell.org
Date: Tuesday, April 21, 2009, 8:53 PM

If you want to just get the value out, meaning you'll get a program error if it happens to be Nothing, then you can use Data.Maybe.fromJust. But usually, you'd want to preserve the Nothing. Applicative or Monad is pretty good for this:
import Control.Applicative
(3+) <$> safeDivision 10 5

the result will be Just 5.0 in this case, but if the division was incorrect it would be nothing.
If you want to do something else, you can either pattern match on it:
case safeDivision 10 5 of  Just x -> -- do something with x  Nothing -> -- do something else
or use some functions from Data.Maybe. Say you want to evaluate to 1 instead of Nothing:
import Data.Maybe
fromMaybe 1 (safeDivision 10 5)
-Ross
On Apr 21, 2009, at 8:49 PM, michael rice wrote:
How do I get the x out of Just x?

Michael

=============

safeDivision :: Float -> Float -> Maybe Float 
safeDivision x y = if y == 0 then Nothing else Just (x/y)

*Main Data.List> safeDivision 10 5
Just 2.0
*Main Data.List> 3 + (safeDivision 10 5)

<interactive>:1:0:
    No instance for (Num (Maybe Float))
      arising from a use of `+' at <interactive>:1:0-22
    Possible fix: add an instance declaration for (Num (Maybe Float))
    In the expression: 3 + (safeDivision 10 5)
    In the definition of `it': it = 3 + (safeDivision 10 5)
*Main Data.List> 


       _______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe at haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe




      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090421/ead3a766/attachment.htm


More information about the Haskell-Cafe mailing list