Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Here is how it can be done in Haskell.

Instead of using a Boolean, use a type that means what you actually want: You want to short-circuit combine two (or more) values, returning the first one that is valid, without evaluating the later ones.

You need a type that represents a possibly-unavailable value. "Boolean" is not that type. "Maybe" is Haskell's type-safe "Nullable" type. It has two kinds of values: "Nothing" or "Just a", where "a" is a value of any type.

Some quick simplified definitions of Haskell terms: "Control.Monad" is Haskell's generalization of "flow control" "mplus" is Haskell's generalization of "or" (as it means in Perl/Python).

backticks are used to make a regular prefix function into an infix operator.

"undefined" is like Perl's "die" or Java's uncatchable Exception, used here to show where short-circuit happens.

ghci is a Haskell interpreter.

  % ghci

  > import Maybe

  > import Control.Monad

  > undefined `mplus` Just 1

  *** Exception: Prelude.undefined

  > Just 1 `mplus` undefined
  
  Just 1

  > Nothing `mplus` (Just 1) `mplus` undefined

  Just 1 

  > Nothing `mplus` (Just 1) `mplus` (Just 2) 

  Just 2
This web page goes into a bit more detail on this technique: http://www.engr.mun.ca/~theo/Misc/haskell_and_monads.htm

It's slightly complex to understand, since it so generalized, but in practice it makes for simple, safe code.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: