Sep 27, 2010

Haskell class declarations

Haskell class is not like classes in Java or c++.
Haskell got many numeric types, which are Int, Integer and Float. You can compare two numbers of the same type for equality but in not different types. Also you can compare two values of type Bool for equality, but you cannot add them together. A class is a template for types, and it gives the operations that the types must do.

class Eq a where
(==), (/=) :: a -> a -> Bool
It defines the == and /= functions.

Simple type decleration

plus :: Int -> Int -> Int
plus x y = x + y

This plus function will get 2 Int numbers, do the calculation and then it will return an Int too.

Monad
This is a very useful concept in haskell.
It,
Do an action from the type of which returns by the function.
Do an action which simply produce a value.
Do a chain "actions" together, while allowing the result of an action to be used for the second action

Maybe

farther :: Person -> maybe Person

This function will return data with type Person or if there is no value it will return nothing.

Note;
let x = foo in bar can writtern as (\x -> bar) foo
x<-foo; bar can writtern as foo>>=(\x -> bar)

Do notation
do putStr "Hello"
putStr " "
putStr "world!"
putStr "\n"

This will print in a sequence.

Then and do notations.

do action
other_action
yet_another_action

This is written by only using do naotation. but this can be wriiten by using bothe do and then notations like this;

action >>
do other_action
yet_another_action

msum

msum :: MonadPlus m => [m a] -> m a
msum = foldr mplus mzero

No comments:

Post a Comment

Your comments are always welcome ...