Haskell ? : The ternary operator


? :: Bool -> (t, t) -> t
a ? (b, c) = if a then b else c

And there you have the Haskell ternary operator. Nice syntax, and lazy evaluation means that only one of b or c is ever evaluated!

Advertisements

~ by hellfeuer on April 11, 2008.

4 Responses to “Haskell ? : The ternary operator”

  1. With what precedence and associativity, though?

  2. what you wrote is no valid haskell code. You can’t use ? as identifier and even if you would replace it by something else, the syntax is still invalid.

  3. Sorry but all of it is perfectly valid.. I’ve been using it in my code.

    Fire up ghci and try for yourself

  4. On GHCi 6.12.3, I have to wrap the ? around parentheses:

    (?) :: Bool -> (t, t) -> t
    a ? (b, c) = if a then b else c

    Otherwise I get a parsing error.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: