Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does haskell have a conditional operator such as "x == y ? a : b" in C++ or ifelse(x==y, a, b) in R?

Does haskell have a conditional operator that performs as

x == y ? a : b

in C++ or

ifelse(x==y, a, b)

in R ?

like image 271
daj Avatar asked Apr 24 '15 14:04

daj


People also ask

Which is the conditional operator used in C?

We use the ternary operator in C to run one code when the condition is true and another code when the condition is false.

Which is an conditional operator?

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.

Does Haskell have ternary operator?

With a bit of work, we can define a ternary conditional operator in Haskell.

What is Haskell operator?

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).


3 Answers

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"

like image 102
leftaroundabout Avatar answered Sep 28 '22 10:09

leftaroundabout


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..

like image 29
madjar Avatar answered Sep 28 '22 10:09

madjar


There is the bool function in Data.Bool:

import Data.Bool
bool b a (x == y)
like image 44
Lee Avatar answered Sep 28 '22 09:09

Lee