LWN.net Logo

RE: nullable pointers

RE: nullable pointers

Posted Apr 1, 2011 21:01 UTC (Fri) by mathstuf (subscriber, #69389)
In reply to: RE: nullable pointers by paulj
Parent article: GCC 4.6.0 released

You still have to case on the empty list (e.g., you can't get the first value from it, so if you need it, you need to do /something/ different for the empty list unless you want exceptions about incomplete pattern matchings). An example:

safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (a:_) = Just a

When calling safeHead, the caller must* check to see if a value was actually returned before using it. This can be done with fromMaybe:

fromMaybe sensibleDefault $ safeHead someList

* The caller can just use fromJust which raises an exception on a Nothing value, but that's the caller's burden at that point.


(Log in to post comments)

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds