w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Understanding Haskell Pattern Matching

Here is a hint.

You can solve your problem using if-else statement:

ifThenElse :: Bool -> Int -> Int -> Int
ifThenElse p x y = if p then x else y

But, Bool is enumerated type with only two values. You can match ifThenElse's arguments with Bool values and define what to do if function gets False or True. It's called pattern-matching:

ifThenElse :: Bool -> Int -> Int -> Int
ifThenElse False = ...
ifThenElse True  = ...

And at last, if you use pattern-matching and in some case resulting value doesn't depend from particular argument, you can hide that argument using placeholder:

f :: Int -> Int -> Int -> Int
f 0 x y = x + y
f 1 _ y = y -- in case of getting `1` function returns just `y`

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.