Monthly Archives: October 2014

Using “if” without writing “if then else”

Haskell has a keyword if which allows you to branch your execution based on some predicate.

if is not a regular function. It might be more useful if it was.

Say i want to replace all occurrences of a character in a string. similar to the unix too sed.

this could be written like this

> let replace x y xs = map (\z->if z==x then y else z) xs

> replace '.' '!' "Yes. I agree."
"Yes! I agree!"

However, what if I want to write it using less points? Because if is not a regular function I can’t use it on its own.

The function if' can easily be written as follows.

> let if' p a b = if p then a else b

Now replace can be re-written as

> let replace x y xs = map (if'.(x==)>>=($y)) xs

much better.