[Haskell-beginners] How do I return Nothing from a function?

Kyle Murphy orclev at gmail.com
Mon Apr 21 18:30:50 UTC 2014


Your problem is that you're explicitly saying that weight can NEVER fail to
return a value, so in the case that you run into a Nothing value you need
to return some default value instead. Alternatively you could change the
signature of weight to instead return a Maybe t type instead. If it's the
former, you need something like:

weight x y g = case g!(x,y) of
  Just w -> w
  Nothing -> 0 -- default weight here

or more idiomatically:

weight x y g = maybe 0 id (g!(x,y))

Not sure if you need the parens around g!(x,y) in that expression, but I
put them in just in case.


-R. Kyle Murphy
--
Curiosity was framed, Ignorance killed the cat.


On Mon, Apr 21, 2014 at 1:53 PM, KC <kc1956 at gmail.com> wrote:

> How do I return Nothing from a function?
>
> When there is no edge in the graph this code fails.
> *** Exception: Graph.hs:65:9-26: Irrefutable pattern failed for pattern
> (Data.Maybe.Just w)
>
>
> *Main> :t weight
> weight
>   :: (Ix t1, Ix t2) => t1 -> t2 -> Array (t1, t2) (Maybe t) -> t
>
> weight x y g = w
>     where
>         (Just w) = g!(x,y)
>
>
> Thank you for your time.
>
>
> --
>
> --
>
> Sent from an expensive device which will be obsolete in a few months! :D
> Casey
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140421/65f63d68/attachment.html>


More information about the Beginners mailing list