Difference between revisions of "Ternary operator"

From HaskellWiki
Jump to: navigation, search
(Further reading: fix user guide link)
 
Line 34: Line 34:
 
== Further reading ==
 
== Further reading ==
   
* [http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#rebindable-syntax Rebindable syntax]
+
* [https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-RebindableSyntax Rebindable syntax]
 
* [http://www.eecs.usma.edu/webs/people/okasaki/pubs.html#hw02 Techniques for Embedding Postfix Languages in Haskell]
 
* [http://www.eecs.usma.edu/webs/people/okasaki/pubs.html#hw02 Techniques for Embedding Postfix Languages in Haskell]
   

Latest revision as of 05:44, 23 July 2020

With a bit of work, we can define a ternary conditional operator in Haskell. Courtesy of Andrew Baumann. This appears only to be valid in Hugs?

import qualified Prelude

data Cond a = a : a

infixl 0 ?
infixl 1 :

(?) :: Prelude.Bool -> Cond a -> a
Prelude.True  ? (x : _) = x
Prelude.False ? (_ : y) = y

test = 1 Prelude.< 2 ? "yeah" : "no!"

Another version that works in GHC.

data Cond a = a :? a

infixl 0 ?
infixl 1 :?

(?) :: Bool -> Cond a -> a
True  ? (x :? _) = x
False ? (_ :? y) = y

test = 1 < 2 ? "Yes" :? "No"

Further reading