Does haskell have a conditional operator that performs as
x == y ? a : b
in C++ or
ifelse(x==y, a, b)
in R ?
We use the ternary operator in C to run one code when the condition is true and another code when the condition is false.
The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows: The first operand is implicitly converted to bool . It is evaluated and all side effects are completed before continuing.
With a bit of work, we can define a ternary conditional operator in Haskell.
Haskell provides special syntax to support infix notation. An operator is a function that can be applied using infix syntax (Section 3.4), or partially applied using a section (Section 3.5).
Apart from if
or Data.Bool.bool
, which do indeed just what you want, you can also define such an operator yourself in Haskell!
infixr 1 ?
(?) :: Bool -> a -> a -> a
(True ? a) _ = a
(False ? _) b = b
GHCi> 3==2 ? "equal" $ "nonequal"
"nonequal"
GHCi> 3==3 ? "equal" $ "nonequal"
"equal"
Haskell's if
performs exactly as you want.
if x == y then a else b
As Lee mentioned, there is a bool
function in Data.Bool
that does the same thing. Also, thanks to Haskell's lazyness, bool someLongComputation something True
does not run the long computation..
There is the bool
function in Data.Bool
:
import Data.Bool
bool b a (x == y)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With