Syntax of Haskell
pattern match
definition
By define a function, we can map some type to another type. Pattern match can apply to any data type: Int, Char, String, etc.
A simple patter match case, mapping a type belong to Integral to String (in other word, it is to match a varible whoes type that belong to Integral):
1 | |
Notation:
- any typevariable like
a,b, …,zorabc,bcd; Then patter will match any numbers but only numbers, for theIntegralin function declaration. This pattern can be also used in other function type, likeChar -> String. Remember to add a catch-all pattern in case of program crash. - Patterns are checked form top to the bottom.
If we writing lucky 'a', it will throw error:
1 | |
which means that Type Char is not a instance of class Integral. (haha, something like instance in OOP ~~)
A factorial function implementation:
1 | |
For that patterns are check from top to bottom, we can’t place the second pattern on the top of the first one. Otherwise, this recursive will never end, for that the seconed catchs all numbers !
usefull pattern
Some useful patterns list as below:
[]: match list(x:[])/[x]: match the first element (It is just a syntactic sugar)(x:xs): match first tox, the rest toxs. In the case, the return type probably be a List. Otherwise it will raise error.(_:xs)matchs non-empty list.
if the pattern consists of several variables, surround them with parentheses.
An example:
1 | |
Another implement of length function with pattern match and recursive:
1 | |
as patterns
Def (as patterns): binding a name refers to the whole thing whilst keep the pattern
An example of use:
1 | |
guards
Def (guards): test if a value satisfies some properties. Something like switch-case- in C programming language.
basic
Just give an axample to see how to use it:
1 | |
each guard | are followed by an boolean expression, if True, then the function is used, if False, jump to the next guard.
otherwiseis of boolean type, the value isTrue- Note that there’s no
=right after the function name and its parameters
where
where in guards, which can be used to make calculations less, an example:
1 | |
align these variables proper in case that Haskell don’t know that
Use where with pattern match, an example:
1 | |
You can also define functions in where section.Code as follows:
1 | |
let-in
Syntax form: let <bindings> in <expression>
An example:
1 | |
Or use it like if statement:
1 | |
Let with list comprehension, then we don’t need to define a additional function.
1 | |
remeber that: Haskell goes from left ro right after pipe
Binding several variables inline need to separater with semicolon, that’s:
1 | |
let-inis local, whilstwhereis visible in all guards.
case-of
The styntax is:
1 | |
A simple example:
1 | |
Pattern matching against something in the middle of an expression example:
1 | |