-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex-1.html
More file actions
846 lines (724 loc) · 74.6 KB
/
index-1.html
File metadata and controls
846 lines (724 loc) · 74.6 KB
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="title" content="shisaa.be (old posts, page 1) | shisaa.be">
<meta name="description" content="A blog about Programming, Unix, Japan and Photography">
<meta name="author" content="Tim van der Linden">
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<title>shisaa.be (old posts, page 1) | shisaa.be</title>
<link rel="alternate" type="application/rss+xml" title="shisaa.be" href="rss.xml">
<link type="image/x-icon" href="assets/img/favicon.ico" rel="icon">
<link type="image/x-icon" href="assets/img/favicon.ico" rel="shortcut icon">
<link href="assets/css/all.css" rel="stylesheet" type="text/css">
</head>
<body id="lang-en">
<div id="rouw" title="Rest quietly, mom. ° 1958 - ✝ 2014"></div>
<div id="wrapper" class="clearfix">
<h1 id="blog-title">
<img src="assets/img/shisaa.png" width="137px" height="160px" alt="shisaa.be Logo depicting a Shisaa demon"><a href="http://shisaa.be/" title="shisaa.be" id="tagline">
<span class="title">shisaa.be</span><span class="interest">web / unix / photography / japan</span>
<span class="en-subtitle">Freelance Developer</span>
</a>
<ul id="translations">
<li class="current-lang first"><span>English</span></li>
<li class="not-first"><a href="ja/index.html" rel="alternate" hreflang="ja">日本語</a></li>
</ul>
</h1>
<input id="mobile-toggle" type="checkbox"><label class="mobile-toggle" onclick="" for="mobile-toggle"></label>
<ul id="sidebar">
<li>
<a href=".">home</a>
</li>
<li>
<a href="stories/about.html">about</a>
</li>
<li>
<a href="stories/services.html">services</a>
</li>
<li>
<a href="archive.html">blog</a>
</li>
<li>
<a href="photography/index.html">photography</a>
</li>
<li>
<a href="stories/3d.html">3D</a>
</li>
<li id="flattr">
<small>Like my material?</small><small>Feel free to <a href="stories/encourage-the-shisaa.html">Encourage the Shisaa</a></small><small id="final-small">She thanks you!</small>
</li>
</ul>
<div id="content">
<div class="index-post">
<h2><a href="postset/chicken-scheme-1.html">The Scheme programming language AKA The CHICKEN hens nest - Part 1</a></h2>
<p class="post-date">23/08/2013 <span>-</span> </p>
<ul class="tags">
<li class="tag"><a href="categories/chicken.html">chicken</a></li>
<li class="tag"><a href="categories/json-rpc.html">json rpc</a></li>
<li class="tag"><a href="categories/scheme.html">scheme</a></li>
</ul>
<div class="index-post-text">
<div>
<h3>Chapter 1 - A Schemey world of wonder</h3>
<p>I just recently finished writing my first egg (module) for the Scheme implementation called CHICKEN.
For me, this seemed as a good point in time to take you on a journey to the world of the Scheme programming language.</p>
<p>The goal of these posts is to show you how to write your own egg for CHICKEN.
Or, in other words, how to contribute and in turn learn about this dialect.</p>
<p>I assume that you have a basic notion of computer programming and know how to use a Unix system on a basic level.
All the rest we can explore in these three chapters!</p>
<p><strong>Beware:</strong> I will fire a lot of information in your general direction...so if you don't understand something, allow yourself to take a step back.
Put these posts down and pick them up a day later. Don't push yourself to read something if you did not understand the part that came before it.</p>
<h4>So what will we see in this first chapter?</h4>
<ul>
<li>A preface</li>
<li>Another preface</li>
<li>What is CHICKEN?</li>
<li>Draw an outline of the egg we will make</li>
<li>Looking at (CHICKEN) data types</li>
<li>Using Medea, an egg for CHCIKEN <-> JSON translation</li>
<li>Learning about cons cells</li>
<li>What are car, cdr and cons?</li>
<li>Start to hatch our egg</li>
<li>Looking at the skeleton of a CHICKEN egg</li>
<li>Using predicates</li>
<li>Looking at exception handling</li>
<li>Take a deep breath and look at what we have seen</li>
<li>Prepare for chapter 2</li>
</ul>
<h3>Preface</h3>
<p>Imagine me and Bill (also known as Bill the Brogrammer) walking down a street on a rainy evening.
Next to us, there is something else walking, a stranger, an unknown.
All of a sudden I turn to Bill and say: "Ever heard of LISP or Scheme?".</p>
<p>Bill gives me a blank stare.</p>
<p>"No? Well, then it's time that I introduce you to each other!"
I take a step back so he can see our stranger and shake its hand.
"Bill, this is Scheme! Scheme, this is Bill!"</p>
<p>But Bill frowns and says: "It looks strange, almost from another planet...and...it looks like my grandfather."</p>
<p>"Now, now, no need to judge so early!", I say, "True that it may look a bit uncommon, and true that it's older then the pilot episode of Lost in Space, but that does not mean a thing!".</p>
<p>Bill looks closer into it's luminescent little eyes and states in a monotone voice: "If I befriend it, people will frown upon me. People will think that I'm smug, a weeny, something better then they are, they will hit me with sticks and chaise me with pitchforks...".</p>
<p>"All of that...just because you have befriended Scheme?", I ask a bit confused.</p>
<p>"Yes! If I come too close to it, I may loose interest in my other friends, especially my good friends Pee-hey-pee<sup>1</sup> and Jaabaa<sup>1</sup>."</p>
<p>I snuggle ever so slightly: "What did <em>those</em> friends ever do for you?"</p>
<p>"<em>Those</em> friends gave me scripts, a corporate look...and...a shiny bandwagon to ride on together with all my other Brogrammers...", Bills eyes turn watery.
With a small voice he asks: "Does Scheme have a shiny bandwagon too?".</p>
<p>I shake my head: "No, I'm sorry, it does not. But it has something else..."</p>
<p>The Schemy little thing puts out its bony hands, holding out a small box.</p>
<p>"Take the box", I instruct Bill, "Take it and open it up.".</p>
<p>Full with doubt Bill takes the box and slowly opens it. His face becomes lit with a bright, angle-like light. A street choir starts to sing.
From the box rises and ancient figure, elegant, light as a feather. Bill starts to weep, tears streaming from his eyes.
"Its....its...the Lambda!", he bursts out in tears of joy, "I see the light...I see it now...its so beautiful!".</p>
<p>"Yes it is, yes it is." I pat Bills shoulder and the three of us walk of into the moonlight.</p>
<p><em><sup>1</sup><small>fictional languages, any resemblance to real languages is pure coincidence...</small></em></p>
<h3>Less cheesy preface</h3>
<p>Okay, that last part may have been a little bit over the top...</p>
<p>But before we dive into Scheme I want to take away the strange light that this language and its users are being put in by some people.
It is true that Schemers (people using Scheme) are smug-lisp-weenies (or smug-scheme-weenies or even smug-list-weenies, ha!), but that is not a <em>bad</em> thing.</p>
<p>From my personal experience, Schemers have been the best and most competent programmers that I have worked with so far.
And yes, they can be smug, really smug, but only when it is <em>justified</em> to be so. When another language fails horribly, Scheme most of the time has a much better alternative.
A <em>good</em> Schemer is smug by pointing out how it can be done better, safer and faster. A <em>good</em> Schemer will never, ever be smug on a personal level.</p>
<p>Scheme, or it's ancestor LISP, is a language that is designed around a totally different view then most, current programming languages.
It has been around long enough to see the birth of all the current hip and cool languages.
And it goes back all the way to the 1950's, quite close to the birth of the modern day computer. <em>And it is still here.</em></p>
<p>Before I start sounding like and evangelist who should start a Church Of Scheme, there are, of course, other nice and elegant languages.
To name a few: Python, Erlang, Pascal, ... . There are dozens of decent languages out there.
Using Scheme does not exclude you from using other languages or vice versa. It will, however, teach you more about <em>real</em> programming.
If used correctly, Scheme can teach you good practices that you can also use (to a certain extend) in other programming languages.</p>
<p>It's a <em>minimalistic</em> language with an almost human readable notation, without almost any syntax hassle and which invites you, no, <em>encourages</em> you to contribute to extend its functionality.</p>
<p>Good, now that we have that off the table, its time to get our hands dirty!</p>
<h3>What is CHICKEN?</h3>
<p>First things first, what is this CHICKEN I keep referring to?</p>
<p>To understand this we have to take a look at how Scheme is used to form various "dialects".
Scheme itself is rarely found, most of the time it is an interpretation of a <em>specification</em> that you will use to program in.</p>
<p>These so-called dialects are based on specifications that aim at making the different Schemes lightweight languages. This lightweight aspect is in contrast to <em>Common Lisp</em> (Schemes twin survivor of the old LISP mother) which includes everything and the kitchen sink.</p>
<p>The specifications that are used <em>as guidelines</em> to build the various Scheme dialects are called the R<em>n</em>RS specs. And just recently, the first draft for the latest spec (R7RS) was released.</p>
<p>Because <em>anyone</em> with some degree of Scheme knowledge can build its own implementation, there are literally thousands of dialects.
Most of them never make it out of the developers computer though, as they are mere experiments to get to know the language better.
But some do make it out and CHICKEN is one such dialect.</p>
<p>Conjured up by <a href="http://spin.atomicobject.com/2013/05/02/chicken-scheme-part-1/" title="Reddit article about Felix Winkelmann">Felix Winkelmann</a> in 2000, CHICKEN is a Scheme implementation based on the R5RS spec.
It is one of the few Schemes out there with a very rich ecosystem of supporting modules (from now on referred to as <em>eggs</em>) that extend CHICKEN's core functionality.
And in my personal experience, the CHICKEN community consists of very, very friendly people who are always willing to help, whether you are an absolute nooby or a seasoned Schemer.</p>
<h3>How do you "get" CHICKEN?</h3>
<p>Before we can start programming using CHICKEN, we have to install it first.
This can be done on a <a href="http://wiki.call-cc.org/platforms" title="CHICKEN WIKI entry for installing on different platforms.">wide variety of platforms</a> ranging from Linux, BSD, OSX and even Windows, but for the scope of these posts I will be using Linux.</p>
<p>On most Linux systems there are binaries available that you can use to get up and running quickly.</p>
<p>I use Arch Linux as my main development platform, so I will stick to that for setting everything up.
To install CHICKEN you can simply let your package manager do the heavy lifting:</p>
<pre class="code literal-block">pacman -S chicken
</pre>
<p>That's it! You now have a fully functional CHICKEN system.</p>
<p>There are three programs that have been installed that you should take note of:</p>
<ul>
<li>csc: The <em>C</em>HICKEN <em>S</em>cheme <em>C</em>ompiler</li>
<li>csi: The <em>C</em>HICKEN <em>S</em>cheme <em>I</em>nterpretor</li>
<li>chicken-install: The chicken egg installer</li>
</ul>
<p>Let us go over them briefly.</p>
<h4>csc</h4>
<p>This is the <em>CHICKEN compiler</em> and is used to "convert" or compile Scheme code into raw C.</p>
<p><em>What is compiling, you ask?</em></p>
<p>Before the day of C, PASCAL or FORTRAN (which are all referred to as "low level" programming languages) you had to completely rewrite you code for every different architecture that you wanted your program to run on. This was a big, time consuming hassle and the computing industry needed something more flexible, something more <em>portable</em>. A <em>generic</em> language that programmers could use. The C programming language was born. Well, to be more accurate, FORTRAN was first, and is considered the oldest language still in use. But because FORTRAN is more in the field of scientific computing, C became a more popular general purpose language to program in.</p>
<p>This introduced a more fluid way of working but also introduced an extra step before you could run your portable code on a specific architecture.
This step is called <em>compiling</em>. Because the different chipsets still needed their own, specific instructions the code still needed to be converted into their supported <em>binary</em> format.</p>
<p>To this day of age, this principle is unchanged. We are still stuck to the same multi architectural differences. Computers haven't actually evolved much since the old days.</p>
<p>Because by modern day standards C itself isn't the most practical, friendly nor safe language to program in, the same idea happened here as well.
So called "high level" programming languages where build on top of C (or along side C) that where more soothing to program in.</p>
<p>And yet another step was introduced.</p>
<p>Before these high level languages could be run by the computer, most of them have to be compiled to portable C code which, in turn, compiles it to architecture specific binary code.
The compilation to C is, in most cases, necessary because the C compiler is one of the few compilers that knows almost <em>every</em> dirty, nitty gritty detail about every chipset, every instructions set available out there. If you want to cut out the C compiler and compile directly to binary code, you will have to implement <em>every goddamn</em> chipset yourself. Since this is generally considered the work of a mad man, people tend to use the C compiler in the final step to spit out binary code.</p>
<p>And that is exactly what happens with the CHICKEN compiler. You compile your Scheme code to portable C code, and then use a C compiler (usually GCC) to compile to a binary file.</p>
<p>What is interesting for us in this stage is the optimization that happens before <em>csc</em> compiles the portable C code.
This is an in-between step that will produce a more optimized version of your CHICKEN code so that the compiler can make more smart decisions.
The optimization step gives as a nice report at the end of the optimized CHICKEN file which we can read and use to "clean up" our source code.</p>
<p>Don't worry about this too much, it will be more clear when we actually come to this step in chapter 2.</p>
<h4>csi</h4>
<p>This is the <em>CHICKEN interpreter</em> and is used to quickly throw some code at and see the results without the need to compile everything.
Another name for this is a <em>REPL</em>, which is short for <em>R</em>ead, <em>E</em>valuate and <em>P</em>rint <em>L</em>oop:</p>
<ul>
<li>You punch in a line of code that it <em>reads</em>
</li>
<li>The interpreter goes and <em>evaluates</em> that code</li>
<li>It <em>prints</em> the result of that evaluation</li>
<li>Then it goes back into read mode, waiting for your input and thus making a <em>loop</em>
</li>
</ul>
<p>You will be using the REPL a lot when developing. Keep in mind though that the interpreter is considerably slower then when you compile your code. So, in CHICKEN at least, its perfect for development purposes, but not for use in "the real world". </p>
<h4>chicken-install</h4>
<p>This is the <em>CHICKEN Egg installer</em> which you can use to...well...install eggs and extend the functionality of your local CHICKEN install.</p>
<h3>Outlining the Egg</h3>
<p>Okay, now that we have the basics up and running on our system, its time to build a clear picture of what we want to make.</p>
<p>In my case, I wanted to build an egg that would format user input (the user here being the programmer using this egg) into a JSON-RPC 2.0 valid string.</p>
<p>If you don't know what JSON is, keep reading!</p>
<p>I found that there was no such egg available in the <a href="http://wiki.call-cc.org/chicken-projects/egg-index-4.html" title="Index of CHICKEN v4 eggs">egg index</a>, so I decided to write it myself and do a contribution to the CHICKEN ecosystem.</p>
<p>This egg is actually part of a larger plan I have in mind, that is, to control my XBMC media box from a terminal application.
In my mind, this larger plan would consist out of three eggs:</p>
<ul>
<li>
<p><em>A JSON-RPC translator</em> (the one we will build now):
The XBMC system uses JSON to let other devices communicate with and control it. So on a basic level we need the instructions that we sent to be valid JSON-RPC.</p>
</li>
<li>
<p><em>A XBMC API in CHICKEN</em>:
XBMC has an elaborate API, in JSON of course, that we have to abstract into Scheme. This is done with the help of the JSON-RPC egg.</p>
</li>
<li>
<p><em>An end-user program</em>:
A program, which implements the above XBMC in Scheme API, that the end-user can actually use to control their XBMC box.</p>
</li>
</ul>
<p>But for now, you can forget about the last two and focus on the JSON-RPC egg.</p>
<p><em>What is JSON?</em></p>
<p>JSON is an acronym for <em>Javascript Object Notation</em> and is a standardized way to exchange textual information between systems. It's as simple as that.
It uses the JavaScript language representation of data and puts in it a serialized form we call a string.</p>
<p><em>Then, what is a JSON-RPC string?</em></p>
<p>JSON-RPC is a <a href="http://www.jsonrpc.org/specification" title="JSON-RPC version 2.0 specification">specification</a> that standardizes a way of invoking RPC's or <em>Remote Procedure Calls</em>. RPC is nothing more then a fancy term which means the same as a way to start a "procedure" on another machine.
Because we are dealing with data <em>exchange</em> we have a client and a server part:</p>
<ul>
<li>Client:
The client can send a <em>request</em> object to the server</li>
<li>Server:
The Server can send back a <em>response</em> object if the request object was understood and an <em>error</em> object if the request was in error.</li>
</ul>
<p>Since the JSON-RPC egg that I made only focuses on the client side (for now) we can concentrate on the <em>request</em> object only.
According to the spec the request string consists out of four different entities where one entity is optional:</p>
<ul>
<li>A string containing the JSON-RPC <em>version number</em>
</li>
<li>A string containing the <em>method</em>
</li>
<li>An <em>optional</em> array (named or positional) containing the <em>parameters</em> (called params)</li>
<li>A unique <em>ID</em>
</li>
</ul>
<p>So a JSON string build according to this spec would look something like this:</p>
<pre class="code literal-block"><span class="p">{</span><span class="nt">"jsonrpc"</span><span class="p">:</span> <span class="s2">"2.0"</span><span class="p">,</span> <span class="nt">"method"</span><span class="p">:</span> <span class="s2">"subtract"</span><span class="p">,</span> <span class="nt">"params"</span><span class="p">:</span> <span class="p">[</span><span class="mi">42</span><span class="p">,</span> <span class="mi">23</span><span class="p">],</span> <span class="nt">"id"</span><span class="p">:</span> <span class="mi">1</span><span class="p">}</span>
</pre>
<p>What we want our egg to do is to accept, in some form, some data (version, method, params and id), construct this JSON string and finally output it.</p>
<p>But how?</p>
<h3>(CHICKEN) Data types</h3>
<p>CHICKEN does not output JSON, even more so, CHICKEN does not <em>know</em> JSON. To CHICKEN, JSON is just a string containing a bunch of characters.
So to be able to work with JSON inside of CHICKEN, it's important that we think of a way we can represent JSON in CHICKEN.
This representation is done trough CHICKEN data types.</p>
<p><em>Data types?</em></p>
<p>Every programming language has data types. They are vital building blocks. A data type is a defined <em>container</em> which can hold a specific type of data.
The data type <em>number</em> (in Scheme), for example, can only hold integers or the data type <em>boolean</em> can only hold true or false.
They tell the system something about the data they contain.</p>
<p>In the world of programming languages we have two data type systems:</p>
<ul>
<li>Dynamically typed (Scheme (CHICKEN), Python, Erlang, JavaScript, Ruby ...)</li>
<li>Statically typed (C, Haskell, Pascall ...)</li>
</ul>
<p>There is <em>great</em> discussion as to which type system is better (not to mention the subtypes "weak" and "strong").
I'll not go into the hairy discussion (for it is unshavably hairy), let us just settle by saying that both systems have their advantages.</p>
<p>With a <em>strong dynamically</em> typed language like CHICKEN, the type is added to the value and not to the variable itself. So you can put a string into a variable that held a number before, but you cannot, for instance, add up a number type (1) and a string type (containing the character 1). It catches programming errors early (during compilation) and puts in a layer of security (data and data types cannot be mixed up). </p>
<p>For now I would be happy if you just remember there are two types and CHICKEN is of the dynamic kind.</p>
<p>So what we have to do next is look at which data types we can use to represent a JSON-RPC valid string in Scheme.</p>
<h3>Medea, the JSON egg</h3>
<p>As we have seen before JSON is a JavaScript based textual representation of data which means that JavaScript is the only language where a JSON string <em>does</em> make sense.
Actually, a JSON string contains JavaScript data types!</p>
<p>Having this info we don't have to figure out everything by ourselves, we just need to make a mapping from JavaScript data types to CHICKEN data types and we have our representation.</p>
<p>Simple, right? Even more simple with an egg called <a href="http://wiki.call-cc.org/eggref/4/medea" title="The Wiki entry for the Medea egg.">Medea</a>.</p>
<p>This egg does <em>exactly</em> what we described above: map JSON (JavaScript) data types to CHICKEN data types and the other way around.</p>
<p>Whoohoo!</p>
<p>But Medea does a conversion for almost <em>every</em> data type, so first we have to look at which data types we actually need.
Since our starting point is an existing JSON-RPC string we have to start by looking at the JavaScript side of things.
Let us introduce a XBMC JSON-RPC string to dissect:</p>
<pre class="code literal-block"><span class="p">{</span><span class="nt">"jsonrpc"</span><span class="p">:</span> <span class="s2">"2.0"</span><span class="p">,</span> <span class="nt">"method"</span><span class="p">:</span> <span class="s2">"Player.PlayPause"</span><span class="p">,</span> <span class="nt">"params"</span><span class="p">:</span> <span class="p">{</span> <span class="nt">"playerid"</span><span class="p">:</span> <span class="mi">0</span> <span class="p">},</span> <span class="nt">"id"</span><span class="p">:</span> <span class="mi">1</span><span class="p">}</span>
</pre>
<p>In this string we find two different JavaScript data types:</p>
<ul>
<li>A string</li>
<li>An object</li>
</ul>
<p>Not too shabby, hey? Just two data types we have to concern ourselves with. If we feed these two data types to Medea, what will it spit out?</p>
<ul>
<li>A string becomes a <em>string</em>
</li>
<li>An object becomes a <em>associative list</em> or <em>alist</em> in short.</li>
</ul>
<p>Also, not too much to handle.</p>
<p>Actually, according to the JSON-RPC spec, we can have an object <em>or</em> an array.
The object can be used to give <em>named</em> params (as in the example above), the array can be used to gives <em>positional</em> params. In CHICKEN a <em>positional</em> array can be translated to a <em>vector</em></p>
<p>So we actually have three data types to look at. Still not too bad!</p>
<p>Let us look at each of them and see what they look like in CHICKEN.</p>
<p>A string in CHICKEN looks like this:</p>
<pre class="code literal-block"><span class="s">"This is a string"</span>
</pre>
<p>Just the same as in most languages. A sequences of characters wrapped in double quotes.
On to the next one, a vector (this would be a normal array in another language):</p>
<pre class="code literal-block"><span class="o">#</span><span class="p">(</span><span class="s">"foo"</span> <span class="s">"bar"</span><span class="p">)</span>
</pre>
<p>This is a vector containing two strings. It is represented as a list proceeded with a hash symbol.
And finally an associative list (this would be a hash table or associative array in another language):</p>
<pre class="code literal-block"><span class="p">((</span><span class="nf">foo</span> <span class="o">.</span> <span class="nv">bar</span><span class="p">)</span> <span class="p">(</span><span class="nf">faa</span> <span class="o">.</span> <span class="nv">bor</span><span class="p">))</span>
</pre>
<p>Also, not too scary, just a list containing pairs.</p>
<p><em>Waah, wait, what are all these parenthesis doing there? And what are these lists you speak of?</em></p>
<p>Phew, I thought you would never ask!</p>
<p>These lists and the parenthesis that represent them are a <strong>very</strong> important part of the language syntax.
This is what many programmers (who don't use a Scheme) see as difficult and sometimes define it as incomprehensible.
If you show a piece of Scheme code to a non-Schemer, many time they let out a girly shriek, scared by the hundreds of parenthesis crawling over their screen.</p>
<p>And most of the time their first reaction (after the shriek) is: "How can you even read this stuff?".</p>
<p>The answer is simple: You just <em>do</em>.</p>
<p>In the beginning you will find this strange and maybe less clear to read. But the more you <em>actually program</em> with a Scheme, the more this syntax will start to feel natural.
And eventually you will feel that these lists and parenthesis will free you from the syntax horror that some other languages can bestow upon you.</p>
<p>The reasoning behind these lists lies in history. In the beginning of the post, we talked about Scheme being a remainder of the old LISP mother.
LISP, which is short for <em>LIS</em>t <em>P</em>rocessing, is a language developed in the 1950's by John McCarthy at the MIT University.</p>
<p>In this language (and all the successors) everything is a list (that not entirely true, but let us forget that for now).
In the beginning lists where simply the way this language represented data, but as the language grew more mature, lists quickly proofed to give an excellent solution to something LISP languages are very good at.</p>
<p>What is that you ask? This: <em>code is data and data is code</em>.</p>
<p>I will not be going deeper into this right now as it is beyond the scope of these posts, but just know that this is one of the reasons why Schemers love their parenthesis.</p>
<p>Oh, and one other important thing, Schemers like to refer to lists as <em>s-expressions</em>. Well, actually <em>lists</em> are <em>s-expressions</em> but <em>s-expressions</em> don't have to be <em>lists</em>. In Scheme <em>symbols</em>, <em>vectors</em>, <em>strings</em>, ... are all <em>s-expressions</em>.</p>
<p>Okay, after this very brief run trough history, let us turn back to our data types we just saw.</p>
<p>We have concluded that we want to use the Medea egg to translate our CHICKEN data types in JSON and we have determined which data type we want to use.
The next logical step is too see how we can actually use Medea inside of CHICKEN to do the conversion for us.</p>
<p>Its time to use...the <em>REPL</em>!</p>
<p>Yes, after all this talk, we can finally get our hands dirty!
As we have seen before, the REPL in CHICKEN is called <em>csi</em>, so open up a terminal and punch the command <em>csi</em>.</p>
<p>You will see a small greeting and a blinking cursor waiting for your input.
By default, the interpreter has no extra modules loaded. If we want to use Medea, we first have to load in that module.
So punch in this line and hit enter:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">use</span> <span class="nv">medea</span><span class="p">)</span>
</pre>
<p>And we have....an error. Ah, aren't I a sneaky bastard...CHICKEN does not know this module "Medea" that you want to use. Why? Because we haven't installed it yet.
So leave you interpreter by typing:</p>
<pre class="code literal-block"><span class="o">.</span><span class="nv">q</span>
</pre>
<p>Before you can install any egg, you have to be root.
So become root and install Medea:</p>
<pre class="code literal-block">chicken-install medea
</pre>
<p>Now switch back to your user and start the interpreter again.</p>
<p>It's important to know that when you exit the interpreter it will reset and forget everything you have done in that session.
So you have to load in Medea again. Now it should show a bunch of lines telling you want it imported and return back to read mode.</p>
<p>Every egg in CHICKEN comes with documentation, so its important you read it carefully before using it or asking help on mailings lists or IRC.
According to Medea's documentation we have two procedures we can use to read or write JSON.</p>
<p><em>What's a procedure?</em></p>
<p>A procedure can be compared with a function in another language. It's a bunch of lists that do something, usually return a value.</p>
<p>Small note about <em>lists</em>: I just told you a little lie, I said that procedures are lists, but actually, in CHICKEN, they are only <em>represented</em> as lists and are their own thing entirely when compiled. There is a common misconception that in CHICKEN or Scheme everything is a list. This comes from the old LISP, where this <em>was</em> true. However, one of the things that separates Scheme from LISP is the very fact that <em>not everything</em> are lists anymore. Just keep a mental note of that.</p>
<p>Okay, let us continue.</p>
<p>By loading in the egg we have many new procedures at our disposal.
There are two of them which we can use directly in the REPL to see the conversion in action:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">read-json</span> <span class="nv">datum</span><span class="p">)</span>
<span class="p">(</span><span class="nf">write-json</span> <span class="nv">datum</span><span class="p">)</span>
</pre>
<p><em>Datum</em> is a placeholder used to describe any form of data that can be put there.
Let us take the JSON string we dissected above and see what Medea makes of it.</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">read-json</span> <span class="s">"{\"jsonrpc\": \"2.0\", \"method\": \"Player.PlayPause\", \"params\": { \"playerid\": 0 }, \"id\": 1}"</span><span class="p">)</span>
</pre>
<p>As you know a string in CHICKEN is wrapper in double quotes. JSON also uses double quotes inside its serialized string.
So to not confuse CHICKEN, we have to escape the JSON double quotes. Escaping of characters inside a CHICKEN string is done with a backslash.
If you input this into your interpreter you will get the following output:</p>
<pre class="code literal-block"><span class="p">((</span><span class="nf">jsonrpc</span> <span class="o">.</span> <span class="s">"2.0"</span><span class="p">)(</span><span class="nf">method</span> <span class="o">.</span> <span class="s">"Player.PlayPause"</span><span class="p">)(</span><span class="nf">params</span> <span class="p">(</span><span class="nf">playerid</span> <span class="o">.</span> <span class="mi">0</span><span class="p">))(</span><span class="nf">id</span> <span class="o">.</span> <span class="mi">1</span><span class="p">))</span>
</pre>
<p>Let us take a closer look at this return value as there are some new things hidden here.</p>
<p>We have four pairs, corresponding to the four entities we have in our JSON-RPC spec.</p>
<p>These pairs are also referred to as <em>cons cells</em>, the building blocks of a list inside CHICKEN.
You may notice that the members of each cons cell are separated by a dot. This is the true, correct way of writing down a pair.</p>
<p>Let us first break down the cons cells that are required according to the JSON-RPC spec (version, method, id):</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">jsonrpc</span> <span class="o">.</span> <span class="s">"2.0"</span><span class="p">)</span>
</pre>
<p>This cons cell describes the JSON-RPC spec version we will use, being 2.0.</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">method</span> <span class="o">.</span> <span class="s">"Player.PlayPause"</span><span class="p">)</span>
</pre>
<p>This cons cell describes the method we send to the server, being a string known to the XBMC api.</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">id</span> <span class="o">.</span> <span class="mi">1</span><span class="p">)</span>
</pre>
<p>And here yet another simple cons cell telling which ID this request object will have.</p>
<p>Now let us look at the optional one, the params:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">params</span> <span class="o">.</span> <span class="p">(</span><span class="nf">playerid</span> <span class="o">.</span> <span class="mi">0</span><span class="p">))</span>
</pre>
<p>This cons cell looks different. In fact, it is a cons cell withing a cons cell.</p>
<p>Here we introduce another part of why list notation is useful: <em>hierarchy</em>. You can use lists within lists within lists ...</p>
<p>What the above snippet tells us is that we have a cons cell from which the second element is another cons cell, or I should better say, the <em>cdr</em> is another cons cell.</p>
<h3>car, cdr & cons</h3>
<p>This gives us a nice little bridge to talk about <em>car</em> and <em>cdr</em>, two more vital parts of the Scheme programming language.</p>
<p>In our cons cells we used above we have a <em>car</em>, the <em>first</em> element of the pair and a cdr, the <em>rest</em> of the pair.
Car and cdr are two primitive procedures, introduced by John McCarthy himself, that you have available in every Scheme (or every LISP remainder for that matter).</p>
<p>Both procedures have only one parameter being a list and will return one value being either the first element of the list in case of <em>car</em> or everything <em>but</em> the first element in case of <em>cdr</em>.</p>
<p>There is nothing more to it.</p>
<p>Before you can ask the car or cdr from a pair, you have the <em>have</em> a pair first. So, if you have two primitive elements, say <em>strings</em>, how can we make a pair out of them?</p>
<p>Using <em>cons</em>!</p>
<p>Cons is another primitive procedure that <em>creates</em> a pair.
This procedure takes <em>two</em> arguments and returns the two items <em>consed</em> onto each other.</p>
<p>To demonstrate, try this in the REPL:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nb">cons </span><span class="s">"foo"</span> <span class="s">"faa"</span><span class="p">)</span>
</pre>
<p>It will result in:</p>
<pre class="code literal-block"><span class="p">(</span><span class="s">"foo"</span> <span class="o">.</span> <span class="s">"faa"</span><span class="p">)</span>
</pre>
<p>But the elements don't have to be primitive elements, they can also be lists.
That means we can do this:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nb">cons </span><span class="s">"foo"</span> <span class="o">'</span><span class="p">(</span><span class="s">"faa"</span> <span class="s">"fii"</span><span class="p">))</span>
</pre>
<p>And get this in return:</p>
<pre class="code literal-block"><span class="p">(</span><span class="s">"foo"</span> <span class="s">"faa"</span> <span class="s">"fii"</span><span class="p">)</span>
</pre>
<p>We just consed the <em>atom</em> "foo" onto the list '("faa" "fii").
Not that difficult I would presume!</p>
<p>Well, I haven't told you everything yet.</p>
<p>First, I just threw a new term at you: the <em>atom</em>. An atom in CHICKEN is the most basic <em>s-expression</em> that you can find and <em>almost</em> always <em>evaluates to itself</em>.
If you type the string "foo" inside the REPL, it will return "foo" to you. Meaning the string "foo" evaluates to itself.
Strings, numbers, booleans (true and false) all are atoms and all evaluate to themselves.</p>
<p>There are, however, some atoms that <em>do not</em> evaluate to themselves. The <em>symbol</em> for instance.
The symbol, most of the time, is used as an identifier for a variable, so it evaluates not to its name, but to the values it is referring to.</p>
<p>Second, it is important to know what a cons cell <em>really</em> is, okay, we know it is a pair, but what is the deeper meaning of it?
A cons cell is actually a pair of two <em>pointers</em>, two references to places inside your computers memory.
The car of the cons cell points to the s-expression you want to have as the first element and the cdr points to another s-expression.
In case you have a pair, this is what actually happens:</p>
<pre class="code literal-block"> <span class="nv">----></span> <span class="s">"foo"</span>
<span class="nv">|</span>
<span class="p">(</span><span class="s">"foo"</span> <span class="o">.</span> <span class="s">"bar"</span><span class="p">)</span> <span class="nv">-----></span> <span class="o">'</span><span class="p">()</span>
<span class="nv">|</span> <span class="nv">|</span>
<span class="nv">----></span> <span class="p">(</span><span class="s">"bar"</span> <span class="o">'</span><span class="p">())</span>
<span class="nv">|</span>
<span class="nv">----></span> <span class="s">"bar"</span>
</pre>
<p>The car of the cons cell ("foo" . "bar") points to the atom "foo" in memory.
The cdr points to another list in memory. You don't actually see it, but every (proper) list ends with the empty list '().
So the cdr of this cons cell is actually not "bar" but rather a small list:</p>
<pre class="code literal-block"><span class="p">(</span><span class="s">"bar"</span> <span class="o">'</span><span class="p">())</span>
</pre>
<p>With this profound new knowledge, let us take another peek at the CHICKEN s-expression that Medea gave us.
This time I will indent it a little bit differently:</p>
<pre class="code literal-block"><span class="p">(</span>
<span class="p">(</span><span class="nf">jsonrpc</span> <span class="o">.</span> <span class="s">"2.0"</span><span class="p">)</span>
<span class="p">(</span><span class="nf">method</span> <span class="o">.</span> <span class="s">"Player.PlayPause"</span><span class="p">)</span>
<span class="p">(</span><span class="nf">params</span>
<span class="p">(</span><span class="nf">playerid</span> <span class="o">.</span> <span class="mi">0</span><span class="p">)</span>
<span class="p">)</span>
<span class="p">(</span><span class="nf">id</span> <span class="o">.</span> <span class="mi">1</span><span class="p">)</span>
<span class="p">)</span>
</pre>
<p>This should now look like a piece of cake (nom . nom)!</p>
<p>We have seen how can get from a JSON string to a CHICKEN s-expression, but what about the other way around?
As seen above we can use the following procedure:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">write-json</span> <span class="nv">datum</span><span class="p">)</span>
</pre>
<p>Let us see if we can convert the s-expression we got above back to a JSON string.
This is rather simple:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">write-json</span> <span class="o">'</span><span class="p">((</span><span class="nf">jsonrpc</span> <span class="o">.</span> <span class="s">"2.0"</span><span class="p">)(</span><span class="nf">mathod</span> <span class="o">.</span> <span class="s">"Player.PlayPause"</span><span class="p">)(</span><span class="nf">params</span> <span class="p">(</span><span class="nf">playerid</span> <span class="o">.</span> <span class="mi">0</span><span class="p">))(</span><span class="nf">id</span> <span class="o">.</span> <span class="mi">1</span><span class="p">)))</span>
</pre>
<p>Actually, this is exactly the same s-expression that we got back from Medea!</p>
<p>Well, almost, there is one small detail: we put the whole s-expression inside a <em>quoted</em> list.</p>
<p>This is a small example of the <em>data is code and code is data</em> statement from earlier.
By putting this s-expression inside another list that has a quote before it, CHICKEN knows that this has to be treated as data.
If you drop the quote, CHICKEN will see it as code and try to evaluate it.</p>
<p>It may not seem as much right now...but this is <strong>AWESOME</strong>, ahum...sorry for that.</p>
<p>Good, we now have a <em>basic</em> understanding of how we can use Medea.
We also know what s-expression we have to build in order to be JSON-RPC valid.</p>
<p>What's next?</p>
<p>Now we have to actually <em>construct</em> the code that will build this JSON-RPC valid s-expression.
Also, we have to give the user of our egg an easy to use interface for putting in its data.
We don't want them to be bothered with the whole JSON-RPC and Medea thing, that all happens behind curtains.
We want them to be able to call a simple procedure with a few arguments and be done with it.</p>
<h3>Hatching an egg</h3>
<p>So I think it is time to actually start to create our egg file! <em>Finally!</em></p>
<p>A basic egg in CHICKEN is nothing more then a directory containing four files:</p>
<ul>
<li>
<em>The source code file(s):</em>
This will contain the actual code that makes up your egg</li>
<li>
<em>A setup file:</em>
Contains information on how to compile your egg</li>
<li>
<em>A meta file:</em>
Contains information about the license, author, documentation, title, etc. for your egg</li>
<li>
<em>A release info file:</em>
Contains the location of your egg on a code hosting site and the version(s) you release</li>
</ul>
<p>These last three files only matter for when you are ready to release your egg, stuff we will do in chapter 2 (that rhymes).</p>
<p>For now we can concentrate on building the code for our JSON-RPC egg (the source code file).
Open up your favorite editor and create a file called <em>json-rpc-client.scm</em>.</p>
<p>We know that we want to communicate with a server, this implies we need to <em>talk</em> with the server over a <em>connection</em>. On a OS level, this connection is made by connecting to a <em>port</em>, the same as you are now connected to port 80 of the Shisaa server to read this very post. In CHICKEN ports can be represented by, well, <em>ports</em>. They carry the same name, but are something different of course. The <em>ports</em> in CHICKEN are <em>objects</em> that you can write to or read from. It is even possible to make a <em>connection</em> with <em>ports</em> to a string. You can then wrtie to a string or read from it. In CHICKEN, reading a writing is done from two different ports, the <em>output</em> and the <em>input</em> port.</p>
<p>Because the <em>ports</em> system in CHICKEN is so flexible, we can use it to communicate over a variety of protocols. One of the more common ones is TCP, which is used to communicate with other machines using an <em>IPv4</em> or IPv6<em> address and a </em>physical* port number. Others include HTTP, WebSockets, ...</p>
<p>Our XBMC server, for example, supports three different protocols to communicate over: TCP, HTTP and WebSockets. Since we are writing a <em>general</em> implementation of <em>JSON-RPC</em> we cannot make any assumptions as to which protocol the user wants to use. So for now we don't have to worry about which protocol to use, we only need to make sure one is an input port and the other is an output port.</p>
<p>The other important thing to note is that the server we communicate with supports a certain version of the JSON-RPC specification.
When laying a connection with the server, we also want to declare which version of the spec we want to use.</p>
<p>These three things are all we need to setup a connection and they are all we need to <em>define</em> our procedure that we will call <em>json-rpc-server</em>:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">json-rpc-server</span> <span class="nv">input</span> <span class="nv">output</span> <span class="nv">version</span><span class="p">)</span> <span class="o">...</span> <span class="p">)</span>
</pre>
<p>There we have it, our first line of code and the first line of our procedure. We defined it, set the name to <em>json-rpc-server</em> and gave it three arguments <em>input</em>, <em>output</em> and <em>version</em>. The three dots indicate that this code is not finished yet and thus cannot be copy and pasted into the REPL.</p>
<p>What would be even better is to explicitly set our version to "2.0", because that's the only version we will support in this egg:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">json-rpc-server</span> <span class="nv">input</span> <span class="nv">output</span> <span class="o">#</span><span class="nv">!key</span> <span class="p">(</span><span class="nf">version</span> <span class="s">"2.0"</span><span class="p">))</span> <span class="o">...</span> <span class="p">)</span>
</pre>
<p>Now "version" is set to "2.0" by default and the user can omit it when calling this procedure.</p>
<p>Next we have to write the <em>body</em> (the part of the procedure that holds the actual code) of this procedure, because now it is empty, and thus not quite useful.</p>
<p>The first thing we need in this procedure is to check if the given arguments are valid. And if not valid, give the user some useful feedback.
To check each argument, we can use so called <em>predicates</em>. These are procedures that check their argument and simply return true or false.
Build in to CHICKEN are predicates to check for a valid input-port or output-port, so let us use them to check our first two arguments:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nb">input-port? </span><span class="nv">port</span><span class="p">)</span>
</pre>
<p>and</p>
<pre class="code literal-block"><span class="p">(</span><span class="nb">output-port? </span><span class="nv">port</span><span class="p">)</span>
</pre>
<p>Neat!</p>
<p>For the third parameter, however, we will have to do a little bit more work. Because "version" is something specific to our egg, we will have to make our own predicate.</p>
<p>To do this, simply start to declare a new procedure which we will call <em>is-valid-version?</em>.
It is common to put a question mark behind the name of a predicate to distinguish them from "other" procedures. In contrast with many other languages, in CHICKEN you can use almost <em>any</em> character inside a variable name. So a question mark is perfectly fine! Just don't use characters like <em>(</em>, <em>)</em> or <em>'</em> or you may confuse CHICKEN into thinking it is the start or end of a list. You can, of course, <em>escape</em> characters inside variable names, but you do not have to worry about that now.</p>
<p>From reading the JSON-RPC spec we know that <em>version</em> has to be a string containing exactly "2.0"...so that is what we have to check for:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">is-valid-version?</span> <span class="nv">version</span><span class="p">)</span>
<span class="p">(</span><span class="nb">string=? </span><span class="nv">version</span> <span class="s">"2.0"</span><span class="p">))</span>
</pre>
<p>That's it, we define <em>is-valid-version?</em> with only one argument <em>version</em>.
Next we check with <em>another predicate</em> called <em>string=?</em> if the given argument "version" is equal to "2.0".</p>
<p>Instead of using <em>string=?</em> we could also have used <em>equal?</em>, but <em>equal?</em> is a generic predicate then can not only check strings, but many other types as well.
But because we <em>know</em> that <em>version</em> is a string we can be more specific and only preform a <em>string comparison</em> here.
By doing that, the compiler (who will eventual compile our egg) also has to do less checks and can make some smart shortcuts.</p>
<p>Okay, so now we have three predicates we can use for our three arguments. But <em>how</em> do we use them?</p>
<p>Well, put them inside your procedure!</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">json-rpc-server</span> <span class="nv">input</span> <span class="nv">output</span> <span class="o">#</span><span class="nv">!key</span> <span class="p">(</span><span class="nf">version</span> <span class="s">"2.0"</span><span class="p">))</span>
<span class="p">(</span><span class="k">cond </span><span class="p">((</span><span class="nb">input-port? </span><span class="nv">input</span><span class="p">))</span>
<span class="p">((</span><span class="nb">output-port? </span><span class="nv">output</span><span class="p">))</span>
<span class="p">((</span><span class="nf">is-valid-version?</span> <span class="nv">version</span><span class="p">)))</span> <span class="o">...</span> <span class="p">)</span>
</pre>
<p>The above snippet introduces a new keyword <em>cond</em>. You may already guessed it, it's short for <em>condition</em>.
And as you can see, we have three conditions. All three have to return <em>true</em> or <em>#t</em> for the <em>cond</em> to continue to the next piece of code.</p>
<p>This is already quite okay, but if one of the predicates is <em>false</em> or <em>#f</em>, what happens?
Well, the procedure is stopped, without any feedback to the user.</p>
<p>That is not very nice! We have to be as useable as possible, so we have to tell the user <em>why</em> the code cannot continue.
To do this, we must provide decent <em>exception handling</em>.</p>
<h4>What is exception handling?</h4>
<p>In the world of software, <em>exception handling</em> is a way to respond to a situation that was not expected.
By good usage of these you can prevent your program from a "crash and burn" situation and you can give helpful feedback to your user.</p>
<p><em>Always provide your code with decent exception handing!</em></p>
<p>In CHICKEN <a href="http://wiki.call-cc.org/man/4/Exceptions" title="CHICKEN Exceptions WIKI page">you have various ways</a> of doing so, one of them being <em>signal</em>.</p>
<p>With <em>signal</em> you can raise a <em>continuable</em> exception. This means that the program does not stop, but simply alerts the user and waits for further input.
We can use <em>signal</em> inside a procedure that we make, a custom exception handler that we will construct specifically for setting up a correct JSON-RPC connection.</p>
<p>Let me give you the full code of such an exception handler:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="nv">type</span> <span class="nv">expected</span> <span class="nv">given</span><span class="p">)</span>
<span class="p">(</span><span class="nf">signal</span>
<span class="p">(</span><span class="nf">make-property-condition</span>
<span class="ss">'exn</span> <span class="ss">'message</span>
<span class="p">(</span><span class="nf">sprintf</span> <span class="s">"Cannot setup connection, the ~S is invalid. Excepted ~A type but got ~A."</span>
<span class="nv">type</span> <span class="nv">expected</span> <span class="nv">given</span><span class="p">))))</span>
</pre>
<p>Let us chew this one, piece by piece.</p>
<p>As you are already familiar with, we define a new procedure that I decided to call <em>server-setup-arguments-error</em>, that accepts three arguments.
This procedure calls <em>signal</em> (to make it a continuable exception) which accepts one parameter, in our case <em>make-property-condition</em>.</p>
<p><em>Make-property-condition</em> is a CHICKEN specific procedure that belongs to CHICKEN's <a href="http://wiki.call-cc.org/man/4/Exceptions" title="CHIKEN WIKI entry for exception handling">exception handling system</a>.
It accepts an exception kind <em>'exn</em> and key/value pairs, in our case one pair <em>'message</em> and <em>sprintf</em>.</p>
<p>The <em>'message</em> we construct using the procedure <em>sprintf</em>. The latter may look familiar from other programming languages.
With <em>sprintf</em> you can construct a string with placeholders, and then fill in the placeholders later.
In our case, we fill in these placeholders with the arguments we give to our custom exception handler.</p>
<p>To be able to ue <em>sprintf</em> we have to load in the <em>extras</em> library. To load in libraries or modules, we can use the <em>use</em> procedure as we have seen when loading in Medea on the REPL.
Put this in the top of your file so that the procedures of <em>extras</em> always get loaded in:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">use</span> <span class="nv">extras</span><span class="p">)</span>
</pre>
<p>The placeholders themselves are documented in on the <a href="http://wiki.call-cc.org/man/4/Unit%20extras#sprintf" title="Sprintf WIKI entry">CHICKEN wiki</a>.
We use <em>~S</em> and <em>~A</em> which are stand for <em>writing</em> or <em>displaying</em> the next argument.</p>
<p>What is the difference between <em>writing</em> and <em>displaying</em>?</p>
<p>A very good question! And also an essential question. <em>Writing</em> and <em>displaying</em> are specified in the <em>RnRS</em> Scheme standards and differ in the way they handle outputting the argument they represent. If you <em>write</em> an argument you will put the quoted and escaped representation of, say, a string. With <em>display</em> you will put the <em>unquoted and unescaped</em> representation:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nb">write </span><span class="s">"foo (bar)"</span><span class="p">)</span>
</pre>
<p>Will give you the same, quoted and escaped output:</p>
<pre class="code literal-block"><span class="s">"foo (bar)"</span>
</pre>
<p>Where as</p>
<pre class="code literal-block"><span class="p">(</span><span class="nb">display </span><span class="s">"foo (bar)"</span><span class="p">)</span>
</pre>
<p>Will give you a an unquoted and unescaped output:</p>
<pre class="code literal-block"><span class="nv">foo</span> <span class="p">(</span><span class="nf">bar</span><span class="p">)</span>
</pre>
<p>In our case we wish to display the given and the excepted arguments as there unquoted and unescaped representation.</p>
<p>So now that we have a basic but decent error handling concept, let us see how we can use it if our above predicates turn out to be false.
Let us take a look at the first line of the predicates:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">cond </span><span class="p">((</span><span class="nb">input-port? </span><span class="nv">input</span><span class="p">)))</span>
</pre>
<p>If we simply put our exception handler there, it would look like this:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">cond </span><span class="p">((</span><span class="nb">input-port? </span><span class="nv">input</span><span class="p">)</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"input port"</span> <span class="s">"input-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">input</span><span class="p">))))</span>
</pre>
<p>But now something is not quite correct. If you look closely, the above snipped says: If the give input is indeed a valid input-port then trigger the exception handler.
The is not what we want, we want it to trigger when it is <em>not</em> a valid input-port. How? Simple, we use <em>not</em>:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">cond </span><span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">input-port? </span><span class="nv">input</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"input port"</span> <span class="s">"input-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">input</span><span class="p">))))</span>
</pre>
<p>Now we have "inverted" the condition. If (input-port?) is <em>#f</em>, then trigger the exception handler. If it is <em>#t</em>, just continue to the next line.</p>
<p>If we implement this into all of our predicates, our code would look like this:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">json-rpc-server</span> <span class="nv">input</span> <span class="nv">output</span> <span class="o">#</span><span class="nv">!key</span> <span class="p">(</span><span class="nf">version</span> <span class="s">"2.0"</span><span class="p">))</span>
<span class="p">(</span><span class="k">cond </span><span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">input-port? </span><span class="nv">input</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"input port"</span> <span class="s">"input-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">input</span><span class="p">)))</span>
<span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">output-port? </span><span class="nv">output</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"output port"</span> <span class="s">"ouput-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">output</span><span class="p">)))</span>
<span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nf">is-valid-version?</span> <span class="nv">version</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"version"</span> <span class="s">"2.0"</span> <span class="nv">version</span><span class="p">)))</span> <span class="o">...</span> <span class="p">)</span>
</pre>
<p>We have three predicate checks (one for every argument), with three exception handlers of the same kind that we call with slightly different arguments depending on the situation.</p>
<p>Among the three arguments that we give to our custom exception handler is hidden another procedure (get-type) that gets one argument.</p>
<p>Why is that?</p>
<p>Well, as we said before, we want to be as helpful to our users as we can, that is one of the main reasons that we want to use decent exception handling.
But I wanted to go a small step further by making a message that gives a little bit more information about the arguments the user entered.</p>
<p>In this case, I want to tell the user which data type I expected and which data type they gave the procedure.
For this I created so called <em>helper function</em>, <em>helper procedure</em> or <em>helper</em> that checks which data type the given argument is and returns some information that we can print it in our message.</p>
<p>As you can see, this <em>helper</em> is called "get-type" and accepts one argument being the argument that the user gave us.
The helper consists of mere predicates for the most common data types we have. It looks like this:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">get-type</span> <span class="nv">x</span><span class="p">)</span>
<span class="p">(</span><span class="k">cond </span><span class="p">((</span><span class="nb">input-port? </span><span class="nv">x</span><span class="p">)</span> <span class="s">"an input port"</span><span class="p">)</span>
<span class="p">((</span><span class="nb">output-port? </span><span class="nv">x</span><span class="p">)</span> <span class="s">"an output port"</span><span class="p">)</span>
<span class="p">((</span><span class="nb">number? </span><span class="nv">x</span><span class="p">)</span> <span class="s">"a mumber"</span><span class="p">)</span>
<span class="p">((</span><span class="nb">pair? </span><span class="nv">x</span><span class="p">)</span> <span class="s">"a pair"</span><span class="p">)</span>
<span class="p">((</span><span class="nb">string? </span><span class="nv">x</span><span class="p">)</span> <span class="s">"a string"</span><span class="p">)</span>
<span class="p">((</span><span class="nb">list? </span><span class="nv">x</span><span class="p">)</span> <span class="s">"a list"</span><span class="p">)</span>
<span class="p">((</span><span class="nb">vector? </span><span class="nv">x</span><span class="p">)</span> <span class="s">"a vector"</span><span class="p">)</span>
<span class="p">((</span><span class="nb">boolean? </span><span class="nv">x</span><span class="p">)</span> <span class="s">"a boolean"</span><span class="p">)</span>
<span class="p">(</span><span class="nf">else</span>
<span class="p">(</span><span class="s">"something unknown"</span><span class="p">))))</span>
</pre>
<p>By now, this sort of thing should not look scary to you at all.</p>
<p>What happens here is we have a <em>cond</em> expression which checks a series of conditions.
If one of the given conditions return true it returns with a string, if none of them are true, the final expression, <em>else</em>, will be returned being <em>something unknown</em>.</p>
<p>To illustrate in further detail how this whole chain of procedures and predicates work, let us assume we call our procedure with an erroneous argument:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="nv">xbmc</span> <span class="p">(</span><span class="nf">json-rpc-server</span> <span class="nv">valid-input</span> <span class="s">"foobar"</span><span class="p">))</span>
</pre>
<p>We call our <em>json-rpc-server</em> procedure with two arguments (version is implicit). Our input-port argument is perfect, our output-port is not so.
What happens in our chain? Let us see step by step:</p>
<p>First the procedure enters the predicate checks. The first one we encounter is our input check:</p>
<pre class="code literal-block"><span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">input-port? </span><span class="nv">input</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"input port"</span> <span class="s">"input-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">input</span><span class="p">)))</span>
</pre>
<p>Since our input-port is correct, this predicate returns true and the <em>cond</em> statement goes to the next line:</p>
<pre class="code literal-block"><span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">output-port? </span><span class="nv">output</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"output port"</span> <span class="s">"ouput-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">output</span><span class="p">)))</span>
</pre>
<p>Now the predicate returns <em>#f</em>, the string "foobar" is not a valid output-port, and thus the <em>not</em> statement is executed.
The <em>not</em> statement has our custom exception handler as its second argument, so that one is called.</p>
<p>While calling this <em>server-setup-arguments-error</em> handler, its arguments are parsed.
The first two are simple strings, but the third is our <em>helper</em> "get-type" with the given output-port as an argument, being the string "foobar" here.</p>
<p>Before we can enter the <em>body</em> of our exception handler procedure, we first have to find out what the return value of "get-type" is.
When we call "get-type" here, it will look like this:</p>
<pre class="code literal-block"><span class="p">(</span><span class="nf">get-type</span> <span class="s">"foobar"</span><span class="p">)</span>
</pre>
<p>Since "foobar" is a string, the following predicate will return <em>#t</em>:</p>
<pre class="code literal-block"><span class="p">((</span><span class="nb">string? </span><span class="nv">x</span><span class="p">)</span> <span class="s">"a string"</span><span class="p">)</span>
</pre>
<p>The argument "x" being our string "foobar". this will make the procedure end and return "a string" to its <em>caller</em>.
Our <em>caller</em> is the exception handler that is waiting for this return value so it can know its third argument and can continue to its <em>body</em>.
We now know this third argument and our call now looks like this:</p>
<pre class="code literal-block"><span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">output-port? </span><span class="nv">output</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"output port"</span> <span class="s">"ouput-port"</span> <span class="s">"a string"</span><span class="p">))</span>
</pre>
<p>So now the exception handler can finally execute and throw an exception with a custom message, constructed with the arguments we gave it.
The messages returned will look like this:</p>
<pre class="code literal-block"><span class="s2">"Cannot setup connection, the output-port is invalid. Excepted output-port type but got a string."</span>
</pre>
<p>Okay, we now have a decent start, we check our user input and respond to it in a correct manner.
It's now time to build the rest of our procedure.</p>
<p>If all the predicates pass, what should happen next?</p>
<p>Well, we want this procedure to return <em>another</em> procedure that the user can use to actually send the commands.</p>
<p>We have seen how we can call our procedure:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="nv">xbmc</span> <span class="p">(</span><span class="nf">json-rpc-server</span> <span class="nv">valid-input-port</span> <span class="nv">valid-output-port</span><span class="p">))</span>
</pre>
<p>Now we have defined <em>xbmc</em>. When we now call <em>xbmc</em>, this will actually be a new procedure waiting for its method and optional params.
Like we said before, when defining <em>json-rpc-server</em>, in this case <em>xbmc</em>, we define the connection.
Later, we can use this connection to send over the commands by calling this new procedure.</p>
<p>You can see it as a keyboard in a box. By correctly calling our <em>json-rpc-procedure</em> we have unlocked the box.
In that box we find a keyboard that is now linked to our server and that we can use to type in our commands (by calling it with correct arguments).</p>
<p>Not making sense yet? Don't worry!</p>
<p>Let us first continue writing our code.</p>
<p>How do we continue after our predicates return <em>#t</em>? When using a <em>cond</em> you can do this by using the <em>else</em> statement.
In our code this would look like so:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">json-rpc-server</span> <span class="nv">input</span> <span class="nv">output</span> <span class="o">#</span><span class="nv">!key</span> <span class="p">(</span><span class="nf">version</span> <span class="s">"2.0"</span><span class="p">))</span>
<span class="p">(</span><span class="k">cond </span><span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">input-port? </span><span class="nv">input</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"input port"</span> <span class="s">"input-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">input</span><span class="p">)))</span>
<span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">output-port? </span><span class="nv">output</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"output port"</span> <span class="s">"ouput-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">output</span><span class="p">)))</span>
<span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nf">is-valid-version?</span> <span class="nv">version</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"version"</span> <span class="s">"2.0"</span> <span class="nv">version</span><span class="p">))</span>
<span class="p">(</span><span class="k">else </span><span class="o">...</span>
</pre>
<p>After this <em>else</em> we can now put the code that will be executed when all the arguments where correct.
Again, we want <em>json-rpc-server</em> to return another procedure that the user can call to actually send something over the wire.
How to we make a procedure return another procedure?</p>
<p>With <em>lambda</em>!</p>
<h4>What is this Lambda?</h4>
<p><em>Lambda</em> or <em>Lambda Calculus</em> is a system in computer programming that allows you to write functions or procedures without naming them.. that's all you need to know for now.</p>
<p>Actually, we have been using lambda's the whole time, I just did not tell you. Every time you declare a new procedure in CHICKEN, you are using a lambda.
When <em>defining</em> a new procedure, we wrote this:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">foo</span> <span class="nv">arguments</span><span class="p">))</span>
</pre>
<p>But this is actually a shorthand for this:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="nv">foo</span>
<span class="p">(</span><span class="k">lambda </span><span class="p">(</span><span class="nf">arguments</span><span class="p">)))</span>
</pre>
<p>But because this is quite a cramp to type every time, we can use the shorthand notation.</p>
<p>Back to our egg, we want our procedure to return a procedure.
Here we cannot use a shorthand, we have to tell it to return a <em>nameless</em> procedure or lambda.
Implementing this, it would look something like this:</p>
<pre class="code literal-block"><span class="p">(</span><span class="k">define </span><span class="p">(</span><span class="nf">json-rpc-server</span> <span class="nv">input</span> <span class="nv">output</span> <span class="o">#</span><span class="nv">!key</span> <span class="p">(</span><span class="nf">version</span> <span class="s">"2.0"</span><span class="p">))</span>
<span class="p">(</span><span class="k">cond </span><span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">input-port? </span><span class="nv">input</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"input port"</span> <span class="s">"input-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">input</span><span class="p">)))</span>
<span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nb">output-port? </span><span class="nv">output</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"output port"</span> <span class="s">"ouput-port"</span> <span class="p">(</span><span class="nf">get-type</span> <span class="nv">output</span><span class="p">)))</span>
<span class="p">((</span><span class="nb">not </span><span class="p">(</span><span class="nf">is-valid-version?</span> <span class="nv">version</span><span class="p">))</span> <span class="p">(</span><span class="nf">server-setup-arguments-error</span> <span class="s">"version"</span> <span class="s">"2.0"</span> <span class="nv">version</span><span class="p">))</span>
<span class="p">(</span><span class="nf">else</span>
<span class="p">(</span><span class="k">lambda </span><span class="p">(</span><span class="nf">method</span> <span class="o">.</span> <span class="nv">params</span><span class="p">))))</span> <span class="o">...</span> <span class="p">)</span>
</pre>
<p>Here is our entire procedure so far, returning a nameless procedure (lambda) if all the given arguments where correct.
And now our story starts over again, well, partially anyway. Since we now enter a new procedure with its own, new arguments, we have to do the same thing as before.</p>
<p>What is that?</p>
<p>Why, check the user input and throw exceptions if needed of course!</p>
<p>But that will be food for chapter 2, for this is already enough to chew on in one chapter.</p>
<p>Congrats if you have made it this far and if you understood my blabberings.
Before I leave you hanging for the next chapter, let us take a quick review of what we have seen:</p>
<ul>
<li>We have seen that Scheme is not so strange as many people think it is</li>
<li>We have seen how we could get CHICKEN installed and running on our system</li>
<li>We have briefly touched on compiling</li>
<li>We have seen an outline of what we want to build in these three chapters</li>
<li>We have seen an egg called Medea for converting CHICKEN data types into JSON data types and vice versa</li>
<li>We have seen how to use this egg to convert both ways</li>
<li>By doing so we have seen what s-expressions, atoms, cons cells, car, cdr and cons are</li>
<li>We have seen the skeleton of an egg</li>
<li>We have laid the basis of our egg and looked at exception handling, predicates and lambdas</li>
</ul>
<p>That's it for know folks. Relax and clear your mind!
If you did not understand something I suggest you go and read it again until the mental light bulb flips on.</p>
<p>The next chapter will be online soon!</p>
<p>And as always...thanks for reading!</p>
</div>
</div>
<ul class="pager">
<li class="previous">
<a href="postset/3d-onsen.html">← Previous post</a>
</li>
<li class="next">
<a href="postset/chicken-scheme-2.html">Next post →</a>
</li>
</ul>
</div>
</div>
<div id="footer">Feel free to drop me a line or to <a href="stories/encourage-the-shisaa.html">Encourage the Shisaa</a>!<br>shisaa.be - © <a href="mailto:tim@shisaa.be">Tim van der Linden</a> 2012~2015 - Powered by <a href="http://nikola.ralsina.com.ar">Nikola</a><br>Twitter: <a target="_blank" href="https://twitter.com/timusan">@timusan</a> - Ohloh: <a target="_blank" href="https://www.ohloh.net/accounts/Timusan">https://www.ohloh.net/accounts/Timusan</a><br> You are reading the footer - So this appears to be the end of this page. <br> I'm bad at saying goodbye...so please scroll back to the top. - And lets pretend you never read this.</div>
</div>
<script src="assets/js/all.js" type="text/javascript"></script>
</body>
</html>