Difference between revisions of "Simple monad examples"
From HaskellWiki
Twobitsprite (talk  contribs) 
m (More minor formatting changes) 

(8 intermediate revisions by 6 users not shown)  
Line 1:  Line 1:  
−  This page is designed to show some simple examples of using 
+  This page is designed to show some simple examples of using [[monad]]s, specifically using [[Maybe]]. 
I personally found that I reached monadenlightenment once I contrived this simple example while playing around to see the "guts" of a monadic expression: 
I personally found that I reached monadenlightenment once I contrived this simple example while playing around to see the "guts" of a monadic expression: 

Line 7:  Line 7:  
</haskell> 
</haskell> 

−  Which results in 
+  Which results in: 
⚫  
+  <haskell>Just 6</haskell> 

+  
+  All you really need to know, is that the <code>(>>=)</code> operator either returns <code>Nothing</code> if it is passed <code>Nothing</code> on its lefthand side; or if its lefthand side is a <code>Just …</code> it strips off the <code>Just</code>, and passes the contents into the function supplied on its righthand side. Simple! 

+  
⚫  
What would the following snippets resolve to? 
What would the following snippets resolve to? 

−  <haskell> 
+  * <haskell> 
Just 0 >>= (\ x > if (x == 0) then fail "zero" else Just (x + 1) ) 
Just 0 >>= (\ x > if (x == 0) then fail "zero" else Just (x + 1) ) 

+  </haskell> 

+  
+  * <haskell> 

Nothing >>= (\ x > if (x == 0) then fail "zero" else Just (x + 1) ) 
Nothing >>= (\ x > if (x == 0) then fail "zero" else Just (x + 1) ) 

</haskell> 
</haskell> 

+  
+   

+  More examples can be found in the reference guide [http://members.chello.nl/hjgtuyl/tourdemonad.html A tour of the Haskell Monad functions], by HenkJan van Tuyl. 

+   

+  [[Category:Monad]] 
Latest revision as of 21:49, 5 April 2021
This page is designed to show some simple examples of using monads, specifically using Maybe.
I personally found that I reached monadenlightenment once I contrived this simple example while playing around to see the "guts" of a monadic expression:
Just 5 >>= (\ x > if (x == 0) then fail "zero" else Just (x + 1) )
Which results in:
Just 6
All you really need to know, is that the (>>=)
operator either returns Nothing
if it is passed Nothing
on its lefthand side; or if its lefthand side is a Just …
it strips off the Just
, and passes the contents into the function supplied on its righthand side. Simple!
Some simple exercises
What would the following snippets resolve to?

Just 0 >>= (\ x > if (x == 0) then fail "zero" else Just (x + 1) )

Nothing >>= (\ x > if (x == 0) then fail "zero" else Just (x + 1) )
More examples can be found in the reference guide A tour of the Haskell Monad functions, by HenkJan van Tuyl.