Haskell walkthrough – II

Pattern matching in functions

One of the big ideas in Haskell is to do pattern matching. Basically you match fn arguments against known patterns. Then you do something for each match. This is useful in breaking out the cases which need to be handled and avoiding big if/else.

Example, here is a simple function:

match 1 = “One”
match 2 = “Two”
match _ = “Unknown input”

When the fn is invoked, the patterns will be checked from top to bottom.

*Main> match 1
*Main> match 3
“Unknown input”

The ‘_’ is a catch all, like the default in Java case statements. Note the type of the function:

*Main> :t match
match :: (Eq a, Num a) => a -> [Char]

Its means that it takes a type ‘a’ as an input and outputs a [char]. In Haskell Strings are just char arrays. We will discuss this more in the write up on types.

Also, note the Type inference at work !

*Main> match ‘x’

    No instance for (Num Char)
        arising from a use of `match’
   Possible fix: add an instance declaration for (Num Char)
   In the expression: match ‘x’
   In an equation for `it’: it = match ‘x’

Here the compiler is complaining that the parameter ‘x’ does not match the type declaration of the function.

Variables in functions

So it turns out that Haskell does allow you to hold some state in a function. Enter the let statement.
The form is: let <bindings> in <expression>.

square x y =
    let xSq = x * x
    ySq = y * y
        in xSq + ySq

*Main> square 2 5


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s