How do I use if-then-else statement with no else condition in Haskell?

  • A+
Category:Languages

I have a list of relations and I wish to print the names of all fathers. Since there's no else condition, the following code doesn't work:

relations = [("father", "arushi", "anandan"), ("mother", "arushi", "abigale"), ("father", "anandan", "ayuta"), ("mother", "anandan", "akanksha")]  father ((r, c, f):xs) = if r == "father" then print(f)  main = do     father (relations) 

I do not wish to put any statement after else.


Too bad, all ifs come with elses. But that's okay, there's a distinguished do-nothing IO action.

father ((r, c, f):xs) = if r == "father" then print f else return () 

There are many other ways to skin this cat. One is pattern matching.

father (("father", c, f):xs) = print f father ((r, c, f):xs) = return () 

Another that is specific to monadic actions is to use when.

father ((r, c, f):xs) = when (r == "father") (print f) 

Of course, that's just hiding the else, which is again return ():

when p act = if p then act else pure () -- okay, it's actually pure, not return 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: