LoginSignup
1
1

More than 3 years have passed since last update.

Approaching Haskell

Posted at

Recently I have been reading programing introduction book of Haskell. Learn some interesting concept and want to write some notes here. I dont expect to master the
functional programming concept only reading once the book. This doc is for note-keeping.

Background

Easy to meta-programming, because creating a type and define how to operate on them is very instinctive

-- new type
Val n

eval Val n = n -- unwrap the primitive in it
(+) Val a, Val b = Val a+b -- operate on the inner primitive and return a Val type wrapping the result

Using Java or python can achieve this goal but class definition is lengthy, tons of getter, setter, factory will calls for boilerplate.

Functor

Like an interface, mainly used to denotes a container type can consume one mapper function. And map in map-reduce idiom is the simple List version Functor working.

-- List is a instance of Functor
map num_list \num = 2 * num     -- a anonymous function to double the var

-- When implement Tree as a Functor, fmap is functor .ver of map(reverse actually)
fmap root_node_of_a_tree node_modifier_function

Applicative

Since Functor can only support mapping single element of the container type. It is a very strong building block but still cannot help a lot.
For exp, if we want a general recursive form of operation that may have side effect(dirty) as well as extend from bifunction to trifunction to N-function. One way is to separate the pure part and apply it to elements in a recursive form, which is Applicative.

-- code bugs
pure = return
inputChars 0 = return
inputChars n = inputChar inputChars n-1

The above sample fit Applicative because inputChar is dirty itself, later part inputChars n-1 do not depend on its side effect.
The impl of Applicative defines how to using the mapping function recursively, but if the mapping function itself may introduce side effect depended by later recursion, we need Monad

Monad

let Maybe = Sure n | Exception
let (div) a b  = a / b

div funciton's type is Num -> Num -> Num
Butn if b = 0 there might be exception, the Haskell way is to use the type Maybe.
In this case we say div function have side effect and its type should be
Num -> Num -> Maybe
But this breaks, because when using div recursively the incoming param can also be Maybe type when exception thrown in former recursions.

Here Monad comes to help. We can define how to bind the type of result when side effects, or other cases occurs.

State Monad

In the form of (a, State), all side effect is stuffed in the State, when we want to receive a pure commputed result from a function, a will place it.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1