full credit to: http://www.alpheccar.org/content/60.html
haskell tutorial

© All Rights Reserved

0 views

full credit to: http://www.alpheccar.org/content/60.html
haskell tutorial

© All Rights Reserved

- Database
- Ramco Sample Paper 2003
- Chapter9 Serialization
- calc
- Assignment C++
- L7 Algorithms and Flowcharts
- abap interview questions & answers
- C++
- Legitbot Function Information
- Program Design
- MIT6_094IAP10_lec02
- 16 - chapter9 - software verification and validation old 11
- 06 Machine Ops Control
- Lecture+20+-+Object+Oriented+Programming
- cis-170c-final-exam.docx
- G Programming Reference Manual
- 2015 Lyp Class 12 Informaticas Practice Delhi Qp
- Visual Basic Ch8
- CS F213 RL 6.3
- Tm246tre.00-Eng Structured Text (St) v3090

You are on page 1of 4

In a lazy functional programming language like Haskell, the order of evaluation

does not matter. It does not mean you cannot control the order of evaluation. It

means you can abstract it and build your own sequencing, your own control.

In imperative languages (like C), you need to extend the language to support new

control statements.

In less elegant functional languages (like LISP) you need to have special forms

which do not follow the normal rules for evaluation.

In Haskell, you "just" build your own control operators. Let's see some examples

:

1.1. Control in IO monad

repeatN 0 a = return ()

repeatN n a = a >> repeatN (n-1) a

test = repeatN 3 $ do

putStrLn "TEST"

And, if you want to pass the loop index to the loop body, you may write:

repeatN 0 a = return ()

repeatN n a = (a n) >> repeatN (n-1) a

test = repeatN 3 $ \i -> do

putStrLn $ "TEST : " ++ (show i)

1.2. Indeterminism monad also known as List monad

Another example of control of the sequencing is the indeterminism monad:

import Control.Monad.List

-- f is a function returning several possible results

f :: Int -> [Int]

f x = [1+x,2*x]

test :: IO ()

test = putStrLn . show $ do

a <- return 5

b <- f a

return b

Here we apply a function f to the value 5. The function f is returning several p

ossible results.

It is possible to chain indeterminate functions like f:

test2 :: IO ()

test2 = putStrLn . show $ do

a <- return 5

b <- f a

c <- f b

return c

but we do not need to give a name to the intermediate results, so let's write it

like:

test2 :: IO ()

test2 = putStrLn . show $ return 5 >>= f >>= f

The Maybe and Either monads are special cases

2. Monad as control of side effects

2.1. IO Monad

It is the standard example so I won't write about it

2.2. Reader monad

A reader monad is used to maintain an environment.

import Control.Monad.Reader

data MyState = MyState { vara :: Int

, varb :: Int

}

-- The initial environment

initState = MyState { vara = 10

, varb = 20

}

-- Computation in the initial environment

test = do theVarA <- asks vara

lift . putStrLn $ show theVarA

`runReaderT` initState

We create a Reader monad to have access to the environment defined by initState.

Then in the monad, we can access the fields of initState.

This state is available whenever we need it in the monad and we do not need to p

ass it as argument.

runReaderT and lift are explained later. They are not important to understand th

is example. You just have to know that the line with lift is used to display a v

alue and the runReaderT is used to initialize the environment.

Now, we can temporarily change the value of one variable and work in this modifi

ed environment.

-- Increment vara from the environment

incrementVarA :: Int -> MyState -> MyState

incrementVarA x p = p {vara = (vara p) + x}

test = do theVarA <- asks vara

lift . putStrLn $ show theVarA

-- computation in the new modified environment

local (incrementVarA 5) $ do

theVarA <- asks vara

lift . putStrLn $ show theVarA

theVarA <- asks vara

lift . putStrLn $ show theVarA

`runReaderT` initState

We have a side effect since the environment is modified and this change is visib

le in a non local way. But this change is nevertheless restricted by the local f

unction.

The previous examples are in fact using the Reader monad and the IO monad hence

the use of the monad transformer ReaderT and runReaderT.

You may use runReader. With runReader the type of test is no more IO () but Int:

test = do theVarA <- asks vara

return theVarA

`runReader` initState

So, an equivalent code (with IO) is:

test = putStrLn . show $ do theVarA <- asks vara

return theVarA

`runReader` initState

runReader has type : Reader r a -> r -> a

It is applying a Reader monad to an initial environment (r).

runReaderT is just a bit more complex. It has type: ReaderT r m a -> r -> m a

So, when you're working in ReaderT r IO a, you need to specify if you are workin

g with values of type ReaderT r IO a or IO a. The lift function is used for this

. Its type is m a -> t m a. So it will transform IO a values to ReaderT r IO a.

A different way to look at this (probably a wrong way) is:

If you have a value v of type a, you use return v to inject it in the ReaderT r

IO a monad.

return v would not work if v was of type IO a since you would get a value of typ

e ReaderT r IO (IO a).

So, lift is used to inject the value in the monad.

3. Monad as container

In each monad, you have the return function which is injecting an element into t

he monad. So, any monad can be seen as a kind of container. For the List monad i

t is obvious. Seeing a monad as a container can be very useful.

Assume you want to add an integer to the result of a computation which could ret

urn no result. You may have to do something like that

result = Just 20

test = case result of

Just a -> Just (a + 10)

_ -> Nothing

So, you need to extract the value from the container (if there is something to e

xtract), apply your function and package the result in the same container.

Or you can just write:

test = (+10) `fmap` result

fmap is a kind of generalization of map. map is lifting a function a -> b to the

container [a] -> [b]

fmap is doing the same for a container m (a monad). So, fmap is transforming the

type a -> b to m a -> m b

4. Deriving monad (you have to use -fglasgow-exts)

In a same code you may have to use different Reader monads even if they have the

same type since they may be for different uses.

You may create a type synonym :

type MyEnvironment a = Reader Int a -- (here the environment is just an Int)

But it would not prevent from mixing two different Reader monads if they have th

e same type.

So, you need to create a new type:

newtype MyEnvironment a = MyEnvironment {runMyEnvironment :: Reader Int a}

Then, you want the same behavior. This is just a reader monad (from a behavior p

oint of view) like newtype Meter = Meter Int is just a number (from a behavior p

oint of view).

So, instead of having to write several instance declarations, you just write:

import Control.Monad.Reader

import Control.Monad.Identity

newtype MyEnvironment a = MyEnvironment {runMyEnvironment :: Reader Int a}

deriving (Monad, MonadReader Int)

Then you create an environment . It is just a Reader monad contained in your new

type

r :: MyEnvironment Int

r = do

r <- MyEnvironment $ ask -- This is packaging the result of ask

-- in MyEnvironment. Hence the work is done

return r -- in the MyEnvironment monad and not in a

-- simple Reader monad r is an Int but

-- return r is a MyEnvironment Int and not

-- a Reader Int Int

Then, you extract the reader monad and apply it to the initial state

test = putStrLn . show $ (runMyEnvironment r) `runReader` 4

5. What's common ?

What do the previous monads have in common ? Nothing ! Or not a lot. Indeed, bei

ng a monad is a very general concept and focusing on the part they have in commo

n (return, >>=) is not the interesting part nor the difficult one. What is inter

esting is how different they are : a Reader monad is providing ask and local fun

ctions ; an IO monad is providing putStrLn etc...

Each monad has its own personality. Of course, >>= will not be the same in each

monad but from a user point of view, it will respect the same monadic laws :

return a >>= k == k a -- return is a "neutral element" on

left

m >>= return == m -- return is a "neutral element" on

right

m >>= (\x -> k x >>= h) == (m >>= k) >>= h -- a kind of associativity of >>=

The only things shared by all monads : the monadic laws.

(This post was imported from my old blog. The date is the date of the import. Th

e comments where not imported.)

- DatabaseUploaded byAnkur Singh
- Ramco Sample Paper 2003Uploaded byncctrtp
- Chapter9 SerializationUploaded byAneesh Kumar
- calcUploaded byVikash Kumar
- Assignment C++Uploaded byKz
- L7 Algorithms and FlowchartsUploaded byAshwini Mathur
- abap interview questions & answersUploaded byPayel Banerjee
- C++Uploaded byFred Austin Hisuan Fabrigar
- Legitbot Function InformationUploaded bymaplelevel2
- Program DesignUploaded bybabe
- MIT6_094IAP10_lec02Uploaded byAnonymous m3tTeasYK
- 16 - chapter9 - software verification and validation old 11Uploaded byapi-237335979
- 06 Machine Ops ControlUploaded bystunningsarath
- Lecture+20+-+Object+Oriented+ProgrammingUploaded byAli Gh
- cis-170c-final-exam.docxUploaded byHazelmcombs
- G Programming Reference ManualUploaded bypelouse23
- 2015 Lyp Class 12 Informaticas Practice Delhi QpUploaded byShivanshu Siyanwal
- Visual Basic Ch8Uploaded byMohammad Ali
- CS F213 RL 6.3Uploaded bySAURABH MITTAL
- Tm246tre.00-Eng Structured Text (St) v3090Uploaded byKaueKoschitzRoratto
- sap 7.4 abap inline codingUploaded byAnonymous Y1csGY
- Consult AsUploaded byalex
- Lesson 4 - Implementing a VI.pdfUploaded byLuis Armando Reyes Cardoso
- Java Main PointsUploaded byAnmol Agarwal
- صف 7 الوحدة 2+3Uploaded byaboubakr3000
- BCA(302)Uploaded bymrajshre.jod
- Flow ControlUploaded byvamsi
- trhhtrhUploaded bySagnikDas
- Practica 3Uploaded byPaulina Mendoza Santos
- Final Assignment - PPL.docxUploaded bynawaz707

- Python - Environment SetupUploaded byBobi Gintoki
- [Guide] MU Offline - Running OFFLINE Server & Client With NO Internet Connection - RaGEZONE - MMO Development CommunityUploaded byNeuro
- python_tutorial(1).pdfUploaded byVinod Nalawade
- Colloquial RussianUploaded byInna Inasaridze
- Haskell TokenizerUploaded byNeuro
- Lisp in HaskellUploaded byNeuro
- Java, C, C++ face growing competition in popularity _ InfoWorldUploaded byNeuro
- Java RMIUploaded byNeuro
- A First Look at Classes in PythonUploaded byNeuro
- Monad Transformers ExplainedUploaded byNeuro
- Monads Again HaskellUploaded byNeuro
- More Control Tools Flow PythonUploaded byNeuro
- Haskell Programming InfoUploaded byNeuro
- 16Uploaded byAnannya Roy
- Phyton InterpreterUploaded byNeuro
- Python Tutorial 234Uploaded byNeuro
- Tuples, Lists and DictionariesUploaded byNeuro
- Haskell State MonadUploaded byNeuro
- Parallel Functional Programming HaskellUploaded byNeuro
- Multithreading in JavaUploaded byNeuro

- Outer SpaceUploaded byKapil Sharma
- Aid and Transition in TajikistanUploaded byNagendra Rao
- STANDARD VETERINARY TREATMENT GUIDELINES (Drug Administration and Control Authority of Ethiopia)Uploaded bySuraj_Subedi
- GeneMapper 4.0 GuideUploaded bypicapenas
- The U.S. Constitution and Money Part 12 The Unconstitutionality of America's Money and Banking SystemUploaded bymichael s rozeff
- s3 Topic 4 Distance Between Two PointsUploaded byPuteri Ayu
- BellyacheUploaded byerin
- Pippin PatternUploaded byHanna Shantala Pontes
- Curriculum Vitae de Arnaldo Claudio (TCA) Reforma PolicíaUploaded byEmily Ramos
- Farewell Letter From Che to Fidel Castro - Che GuevaraUploaded bykashmir
- EC302Uploaded byapi-3853441
- Presentation on Economic Value Added (EVA)Uploaded byrockygoa
- pyfa.txtUploaded byrefrag
- Dental CariesUploaded bymithunjith
- Django TastypieUploaded byChaiyawut_Sook_7280
- Happiness and the Sad Topics in AnthropologyUploaded byMarko Trupković
- article on snm.pdfUploaded bydanikapan
- PW2012MarAprUploaded byInterweave
- Traxxis ManualUploaded byBen Evans
- An Ethnobotanical Survey of MedicinalUploaded byMuchtar Arifin
- 42 Below Case StudyUploaded byPraneil Dahya
- awakening_devos.pdfUploaded bykimmyx21
- Hierarchy in Revenue DepartmentUploaded byhelloandhai
- Benefits of Cold Mix Technology over Hot Mix Technology in Sustainable Road NetworkUploaded byAdvanced Research Publications
- Man Sicam p 7kg775x EnUploaded byClifford Baang
- Legal Status of Eastern Greenland DigestUploaded byPrincess Pumbaya
- Engineering, Procurement and Construction (EPC) Contracts PresentationUploaded byJeff Lambayan
- Hrd Rig ControlUploaded bymdc2013
- AnthrohUploaded byJenelle Catherina Magbutay
- Boral SIlkwood Brochure - Whole RangeUploaded byjonzak1234

## Much more than documents.

Discover everything Scribd has to offer, including books and audiobooks from major publishers.

Cancel anytime.