Difference between revisions of "Ternary operator"
Jump to navigation
Jump to search
(→Further reading: rebindable syntax in the ghc users guide) |
(→Further reading: fix link to "Techniques for Embedding Postfix Languages in Haskell") |
||
Line 35: | Line 35: | ||
* {{GHCUsersGuide|exts/rebindable_syntax||a section on Rebindable Syntax}} |
* {{GHCUsersGuide|exts/rebindable_syntax||a section on Rebindable Syntax}} |
||
− | * [http:// |
+ | * [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.121.1890&rep=rep1&type=pdf Techniques for Embedding Postfix Languages in Haskell] |
[[Category:Code]] |
[[Category:Code]] |
Latest revision as of 23:08, 24 July 2021
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"