-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader-monad-understanding.html
263 lines (221 loc) · 15.2 KB
/
reader-monad-understanding.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml">
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine">
<title>Reader monad understanding - Just a Memo</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="./extra/favicon.ico" rel="icon">
<link rel="canonical" href="./reader-monad-understanding.html">
<meta name="author" content="Alexander Kuleshov" />
<meta name="keywords" content="haskell" />
<meta name="description" content="Some time ago I started to learn Haskell. It's not the first time (and event not second) that I started to learn this language. Every time I met different problems with understanding different abstractions like a Monads, Arrows, Monad Transformers and etc... I think that I'm not alone ..." />
<meta property="og:site_name" content="Just a Memo" />
<meta property="og:type" content="article"/>
<meta property="og:title" content="Reader monad understanding"/>
<meta property="og:url" content="./reader-monad-understanding.html"/>
<meta property="og:description" content="Some time ago I started to learn Haskell. It's not the first time (and event not second) that I started to learn this language. Every time I met different problems with understanding different abstractions like a Monads, Arrows, Monad Transformers and etc... I think that I'm not alone ..."/>
<meta property="article:published_time" content="2014-03-04" />
<meta property="article:tag" content="haskell" />
<meta property="article:author" content="Alexander Kuleshov" />
<!-- Bootstrap -->
<link rel="stylesheet" href="./theme/css/bootstrap.min.css" type="text/css"/>
<link href="./theme/css/font-awesome.min.css" rel="stylesheet">
<link href="./theme/css/pygments/monokai.css" rel="stylesheet">
<link rel="stylesheet" href="./theme/css/style.css" type="text/css"/>
<link href="./feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
title="Just a Memo ATOM Feed"/>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="./" style="color: sienna; font-family: 'Droid Sans'; font-size: 25px;" class="navbar-brand">
Just a Memo </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://twitter.com/0xAX" style="" class="navbar-brand">
<img src="extra/twitter-24.gif" width=""/>
</a>
</li>
<li>
<a href="https://github.com/0xAX" style="" class="navbar-brand">
<img src="extra/github-8-24.gif" width=""/>
</a>
</li>
<li>
<a href="https://kz.linkedin.com/in/alexander-kuleshov-301b7824"
style="" class="navbar-brand">
<img src="extra/linkedin-3-24.jpg" width=""/>
</a>
</li>
<li>
<a href="http://stackoverflow.com/users/274299/0xax" style="" class="navbar-brand">
<img src="extra/stackoverflow-24.jpg" width=""/>
</a>
</li>
<li>
<a href="http://0xax.github.io/atom" style="" class="navbar-brand">
<img src="extra/rss-24.gif" width=""/>
</a>
</li>
<li>
<a href="mailto:kuleshovmail@gmail.com" class="navbar-brand">
<img src="extra/email-12-24.gif" width=""/>
</a>
</li>
<li>
<a href="./archives.html" class="navbar-brand">
<img src="extra/archive-2-24.gif" width=""/>
</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container">
<div class="row">
<div class="col-lg-12">
<section id="content">
<article>
<header style="color: #A0522D;" class="page-header">
<h1 style="color: #A0522D;">
<a href="./reader-monad-understanding.html"
rel="bookmark" style="color: #A0522D;"
title="Permalink to Reader monad understanding">
Reader monad understanding
</a>
</h1>
</header>
<div class="entry-content" style="font-family: 'Droid Sans'; font-size: 17px;">
<p>Some time ago I started to learn Haskell. It's not the first time (and event not second) that I started to learn this language. Every time I met different problems with understanding different abstractions like a Monads, Arrows, Monad Transformers and etc... I think that I'm not alone with this :) But, in this time, I decided not to throw up training until I can not say: yes I can write in Haskell without pain. I started (as every time i did it) with the most popular book (for newbies) about Haskell - Learn You a Haskell and stopped at Reader monad. Spending some time I understand it (at least I think that I understand :)) and decided to share my understanding of this monad for the same newbie haskellers as me.</p>
<p>Let's imagine simple and ubiquitous case that we have application which needs in some initial configurations. Application will get configuration form configuration file, let it be conf.js with very simple structure like this:</p>
<div class="highlight"><pre><span class="p">{</span>
<span class="s2">"username"</span> <span class="o">:</span> <span class="s2">"0xAX"</span>
<span class="p">}</span>
</pre></div>
<p>It just has 1 <code>username</code> key. Of course it has very little resemblance with the real application configuration, but it is not important now and enough for the example. We will read it with great Aeson library from Bryan O'Sullivan and use it in our application. Let's start with reading configuration file content and decoding json.</p>
<h2>Aeson</h2>
<p>For the start we must define data type for mapping json data in it with Aeson. As you can see above, we have simple json structure with username key. So we will map this json structure to the following data type:</p>
<div class="highlight"><pre><span class="kr">data</span> <span class="kt">ConfigStructure</span> <span class="ow">=</span>
<span class="kt">ConfigStructure</span> <span class="p">{</span>
<span class="n">key1</span> <span class="ow">::</span> <span class="kt">String</span><span class="p">,</span>
<span class="n">key2</span> <span class="ow">::</span> <span class="kt">String</span>
<span class="p">}</span> <span class="kr">deriving</span><span class="p">(</span><span class="kt">Generic</span><span class="p">)</span>
</pre></div>
<p>The <code>ConfigStructure</code> has the same structure as our json, it has same fields: username. After data type creation we must read our configuration file with json data and decode it with aeson:</p>
<div class="highlight"><pre><span class="nf">configPath</span> <span class="ow">::</span> <span class="kt">String</span>
<span class="nf">configPath</span> <span class="ow">=</span> <span class="s">"conf.json"</span>
<span class="nf">getConfigContent</span> <span class="ow">::</span> <span class="kt">IO</span> <span class="kt">ConfigStructure</span>
<span class="nf">getConfigContent</span> <span class="ow">=</span> <span class="kr">do</span>
<span class="n">configContent</span> <span class="ow"><-</span> <span class="kt">BSL</span><span class="o">.</span><span class="n">readFile</span> <span class="n">configPath</span>
<span class="kr">let</span> <span class="kt">Just</span> <span class="n">decodedConfig</span> <span class="ow">=</span> <span class="n">decode</span> <span class="n">configContent</span> <span class="ow">::</span> <span class="kt">Maybe</span> <span class="kt">ConfigStructure</span>
<span class="n">return</span> <span class="n">decodedConfig</span>
</pre></div>
<p>Here you can see that we reading json file with readFile function from Data.ByteString.Lazy. It has following type:</p>
<div class="highlight"><pre> <span class="n">Prelude</span><span class="o">></span> <span class="kn">import</span> <span class="nn">qualified</span> <span class="nn">Data.ByteString.Lazy</span> <span class="kn">as</span> <span class="nn">BSL</span>
<span class="n">Prelude</span> <span class="n">BSL</span><span class="o">></span> <span class="p">:</span><span class="n">t</span> <span class="n">BSL</span><span class="o">.</span><span class="n">readFile</span>
<span class="n">BSL</span><span class="o">.</span><span class="n">readFile</span> <span class="p">::</span> <span class="n">FilePath</span> <span class="o">-></span> <span class="n">IO</span> <span class="n">BSL</span><span class="o">.</span><span class="n">ByteString</span>
</pre></div>
<p>where FilePath is just String. Read configuration file and get it's content. After getting content of configuration file using Data.Aeson.decode function for decoding json data from it. After successful decoding we get Just ConfigStructure and now we can build Config data type for Reader and pass configuration file content to it.</p>
<h2>Reader Monad</h2>
<p>And now we come to the main point of this post. Main point of Reader monad to share read-only environment between couple of functions. Let's see how Reader declared in Control.Monad.Reader:</p>
<div class="highlight"><pre><span class="kr">newtype</span> <span class="kt">Reader</span> <span class="n">r</span> <span class="n">a</span> <span class="ow">=</span> <span class="kt">Reader</span> <span class="p">{</span> <span class="n">runReader</span> <span class="ow">::</span> <span class="n">r</span> <span class="ow">-></span> <span class="n">a</span><span class="p">}</span>
</pre></div>
<p>We can see that it made as wrapper for runReader function with type r -> a where:</p>
<ul>
<li><code>r</code> - is a reader which need to run and get final value from it;</li>
<li><code>a</code> - is an environment which need to share</li>
</ul>
<p>Another words we can build abstraction that will share configuration file content between different functions. Let's see how to implement it.</p>
<div class="highlight"><pre><span class="kr">type</span> <span class="kt">Config</span> <span class="ow">=</span> <span class="kt">Reader</span> <span class="kt">ConfigStructure</span> <span class="kt">String</span>
</pre></div>
<p>Here we can see Config type synonym for Reader ConfigStructure String. Here ConfigStructure (see above) will be environment which we will share between functions and String return type. Now we write function for getting value of username field from configuration file:</p>
<div class="highlight"><pre><span class="nf">getKeyOne</span> <span class="ow">::</span> <span class="kt">Config</span>
<span class="nf">getKeyOne</span> <span class="ow">=</span> <span class="kr">do</span>
<span class="n">config</span> <span class="ow"><-</span> <span class="n">ask</span>
<span class="n">return</span> <span class="p">(</span><span class="n">key1</span> <span class="n">config</span><span class="p">)</span>
</pre></div>
<p>As you can see it's pretty simple. Here is only one thing which we don't know - ask function. ask function retrieves the monad environment. Pretty simple. Now we can get username in any place of our application with runReader function. As you can remember runReader function has following type:</p>
<div class="highlight"><pre><span class="nf">runReader</span> <span class="ow">::</span> <span class="n">r</span> <span class="ow">-></span> <span class="n">a</span>
</pre></div>
<p>Where r is a reader which need to run (getKeyOne in our case) and a is environment (configuration file content in our case). Again pretty simple. We can get value of username with:</p>
<div class="highlight"><pre><span class="c1">-- read configuration file</span>
<span class="nf">decodedConfig</span> <span class="ow"><-</span> <span class="n">getConfigContent</span>
<span class="c1">-- get & print value of key1</span>
<span class="nf">putStrLn</span> <span class="o">$</span> <span class="n">runReader</span> <span class="n">getKeyOne</span> <span class="o">$</span> <span class="n">decodedConfig</span>
</pre></div>
</div>
<!-- /.entry-content -->
<div class="panel" style="font-family: 'Droid Sans';">
<div class="panel-body" style="">
<hr style="margin-left: -15px;"/>
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style" style="margin-left: -15px;">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_button_google_plusone" g:plusone:size="medium"></a>
<div style="float: right;"><footer class="post-info">
<span class="label label-default">Date</span>
<span class="published">
<i style="top: -1px; position: relative; margin-top: -1px;" class="fa fa-calendar"></i>
<time datetime="2014-03-04T00:00:00+07:00"> Tue 04 March 2014</time>
</span>
</footer><!-- /.post-info --></div>
</div>
<!-- AddThis Button END -->
</div>
</div>
</article>
</section>
</div>
</div>
</div>
<footer>
<div class="container">
<div class="row">
<div class="col-xs-12" style="float: left;"> <p style="float: right;"><small> <a style="color: #a0522d; float: right;" href="https://github.com/0xAX">@0xAX © 2016</a>
</small></p>
</div>
</div>
</div>
</footer>
<script src="./theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="./theme/js/bootstrap.min.js"></script>
<!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) -->
<script src="./theme/js/respond.min.js"></script>
<!-- Google Analytics -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-64079379-1']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
<!-- End Google Analytics Code -->
<script type="text/javascript">var addthis_config = {"data_track_addressbar": true};</script>
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-53a535f822555b0c"></script>
</body>
</html>