aboutsummaryrefslogtreecommitdiffstats
path: root/chicken.svnwiki
blob: 15bf44a5b78b56153527c9b1ea1b4624e1354e56 (plain) (blame)
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
== HaScheme

A Lazy dialect of Scheme, embedded in Scheme

[[toc:]]

=== Description

''Scheme demonstrates that a very small number of rules for forming expressions, with no restrictions on how they are composed, suffice to form a practical and efficient programming language that is flexible
enough to support most of the major programming paradigms in use today.''

— ''Revisedⁿ Reports on the Algorithmic Language Scheme (n ≥ 3, 1986–)''

HaScheme is a library that implements a subset of the R7RS's libraries in a lazy way, using {{force}} and {{delay-force}}. When HaScheme is used by itself, it is a lazy functional programming language with the same syntax as Scheme, embedded within Scheme. HaScheme is implicitly lazy, and only requires strictness annotations, not laziness annotations. Scheme procedures can be easily wrapped to be used in HaScheme, and Scheme can call {{force}} on HaScheme promises to obtain values from HaScheme.

For instance, the following {{map}} implementation is both valid HaScheme (importing {{(hascheme base)}}) and Scheme (importing {{(scheme base)}}):

<enscript language="scheme">
(define (map f list)
  (if (null? list)
      '()
      (cons (f (car list)) (map f (cdr list)))))
</enscript>

This procedure in HaScheme will return a promise. The function's body is only executed if, when attempting to {{force}} a promise containing the map, the contents of the map are needed for a computation.

Since HaScheme is lazy, one can write infinite lists with it:

<enscript language="scheme">
(let ((N (let loop ((i 0))
           (cons (! i) (loop (+ i 1))))))
  (force (list-ref (map square N) 100))) ; => 100000
</enscript>

This code snippet will run in a constant amount of space. (The procedure {{!}} is a strictness annotation to avoid thunk buildup. Since HaScheme is emedded within a call-by-value language, the strictness annotation will always force {{i}} at every iteration of the loop, even if neither part of the pair is accessed.)

Why use this?

*# To have fun.
*# To show Haskellers that you don't need some fancy static type system to have pervasive lazyness.
*# To implement lazy code that can be used with strict code.

HaScheme does not support continuations, parameters, exceptions, or multiple value returns.

HaScheme works in Chibi too.

=== Author

Peter McGoron

=== Repository

https://software.mcgoron.com/hascheme/

=== Requirements

* [[/egg/r7rs|r7rs]]

=== API

The HaScheme library namespace is structured in a similar way to R7RS-large's namespace, except it does not export any procedure that is side-effecting.

==== {{(hascheme base)}}

Exports everything from {{(scheme base)}} as lazy procedures, except

* {{call/cc}}, {{dynamic-wind}}, {{values}}, {{call-with-values}}
* Any procedure ending with {{!}}
* Anything to do with ports, except for {{eof-object}} and {{eof-object?}}
* {{make-parameter}}, {{parameterize}}
* Anything involving exceptions, except for {{error}}, {{error-object?}}, {{error-object-message}}, {{error-object-irritants}}
* {{for-each}}, {{vector-for-each}}
* {{floor/}}, {{truncate/}}, and {{exact-integer-sqrt}} are exported, but return lists.

The functions act as one would expect they would act. Forcing {{(car x)}} forces {{x}}, but forcing {{(cons x y)}} does not force {{x}} or {{y}}.

Syntax that introduces procedures, like {{lambda}}, {{define}}, and named {{let}} make lazy procedures. Lazy procedures return a promise that when forced, force the body of the procedure.

Bodies are regular bodies: they can have internal {{define}}s.

Note that control syntax like {{if}} and {{cond}} are still syntax. They can be implemented as functions, but then they will have subtly different behavior when it comes to explicitly forcing values. Conditinoals force tests.

String, bytevector, and number constructors are always eager. List and vector constructors are lazy.

This library also exports {{seq}}.

<procedure> (seq x ... y) </procedure>

Forces all arguments except its last argument. Returns its last argument unchanged.

<syntax>(define-record-type name (cstr name ...) predicate? (name accessor) ...)</syntax>

Creates a record type, as if by the regular {{define-record-type}}. This form gives no way to create setters.

The constructor is always non-strict in its arguments, and the accessors always force their arguments.

<syntax>(do ((id init [update]) ...) (condition body ...) inner-body ...)</syntax>

Like the do loop of before, except that the value that {{inner-body ...}} eventually evaluates to is forced for effect. Since {{inner-body ...}} is a body, nothing else is forced for effect. Consider using {{seq}} here.

==== {{(hascheme case-lambda)}}

Exports {{case-lambda}}, which creates lazy procedures.

==== {{(hascheme char)}}

Exports lazy procedure versions of {{(scheme char)}}.

==== {{(hascheme complex)}}

Exports lazy procedure versions of {{(scheme complex)}}.

==== {{(hascheme cxr)}}

Exports lazy procedure versions of {{(scheme cxr)}}.

==== {{(hascheme inexact)}}

Exports lazy procedure versions of {{(scheme inexact)}}.

==== {{(hascheme control)}}

Exports procedure versions of control syntax.

<procedure> (if x y [z])</procedure>
Force {{x}}. If true, return {{y}}. If not, return {{z}} (or an unspecified value).

<procedure>(cond [x y] ...)</procedure>
Force {{x}}. If true, return {{y}}. If not, continue on with the next pairs. If no pairs exist, return an unspecified value.

<procedure>(and x ...)</procedure>
Force {{x}}. If true, force the next value, and so on. If there are no more values, return {{#t}}. If not, return {{#f}}.

<procedure>(or x ...)</procedure>
Force {{x}}. If true, return {{x}}. Otherwise, force the next value, and so on. If there are no more values, return {{#f}}.

<procedure>(when pred . subsequents)</procedure>
Force {{pred}}. If true, run {{(apply seq subsequents)}}. Otherwise return an unspecified value.

<procedure>(unless pred . subsequents)</procedure>
Force {{pred}}. If false, run {{(apply seq subsequents)}}. Otherwise return an unspecified value.

==== {{(hascheme eager)}}

Procedures and syntax forms for eager evaluation.

<procedure> (! x) </procedure>
Shorthand for {{(force x)}}.

<syntax>(define-wrappers-from-strict (head source) ...)</syntax>

Defines lazy-procedure variants of {{source}} that force all arguments. Head can either be {{(name formal ...)}} or {{name}}.

<syntax>(define-wrappers-for-lazy (head source) ...)</syntax>

Define lazy-procedure variants of {{source}} that pass all arguments to a constructor. Head is defined as in {{define-wrappers-from-strict}}.

<syntax>(define-binary-wrapper (wrapper source) ...)</syntax>

Defines {{wrapper}} as a non-strict n-ary comparison function. It will force the first two arguments to it, and if the comparison returns false, the procedure returns false and none of the other values are forced. Otherwise it will keep on forcing arguments until there are no more arguments or one of the comparisons fail.

<syntax>(let*! ((formal expr) ...) body ...)</syntax>
Forces each {{expr}}, binds the result to {{formal}}, and executes {{body ...}}.

<syntax>(let*-seq ((formal expr) ...) body ...)</syntax>
Returns a promise to force each {{expr}}, bind it to {{formal}}, and then execute {{body ...}}.

This library also exports {{seq}}.

==== {{(hascheme lists)}}

This library exports all identifiers from [[https://srfi.schemers.org/srfi-1|SRFI-1]], except for

* {{circular-list?}}
* {{car+cdr}}
* {{length+}}
* {{for-each}}, {{pair-for-each}}, {{map-in-order}}
* {{set-car!}}, {{set-cdr!}}
* {{unzip[n]}} (see below)

All procedures that normally return multiple values return lists.

In addition, this library exports other procedures.

<procedure>(length>=? list n)</procedure>
<procedure>(length>? list n)</procedure>
<procedure>(length<=? list n)</procedure>
<procedure>(length<? list n)</procedure>
<procedure>(length=? list n)</procedure>

Determine the size of the list by looking at only {{n}} elements. This
will decide the size of finite or infinite lists in all cases where {{n}}
is not infinite. All list lengths are less than or equal to infinity,
and all lists are not greater than infinity.

<procedure>(unzip lists)</procedure>

Returns a list, whose first element is the first element of each {{lists}},
the second element is the second element of each {{lists}}, and so on until
the first empty list.

<procedure>(list-iterate proc base)</procedure>

This procedure is based off of the one in [[https://srfi.schemers.org/srfi-41/srfi-41.html|SRFI-41]].

Create an infinite list where the first element is {{(proc base)}}, and
the second element is {{(proc (proc base))}}, etc.

This procedure is eager in {{base}}.

=== Misc. Information

==== How is it implemented?

The implementation follows the formula of [[https://srfi.schemers.org/srfi-45/|SRFI-45]] with some changes for usability.

*# All procedure bodies are implicitly wrapped in {{delay-force}}.
*# Scheme procedures that require their values are, in addition, wrapped such that forcing their function forces the necessary arguments. A Scheme procedure that is a constructor does not force its arguments.
*# Control flow forces the value of the test expression.

Three critical things are needed to make HaScheme ergonomic:

*# Promises are distinct from other types.
*# Forcing a value returns the value.
*# Forcing {{(delay-force x)}} is equivalent to a tail call to {{(force x)}}.

Chicken does all three. There is nothing fancy going on here, just some (relatively) easy-to-understand {{syntax-rules}} macros. There is a shim for implementations that don't offer the above guarantees.

==== Fun (or pain) with Laziness

You need to be careful with lazy functions because they can cause
space leaks. This is a problem in general with lazy languages [[https://wiki.haskell.org/Foldr_Foldl_Foldl%27|likein Haskell]]). Here is an example:

<enscript language="scheme">
(define (list-tail list n)
  (if (zero? n)
      list
      (list-tail (cdr list) (- n 1))))
</enscript>

Thunks will build up over time in the list, so it must be forced.

<enscript language="scheme">
(define (list-tail list n)
  (if (zero? n)
      list
      (list-tail (force (cdr list)) (- n 1))))
</enscript>

Note that {{n}} is never explicitly forced: it is implicitly forced by the
control flow.

The first code block has the attractive property that it operates the
same way on finite lists in both Scheme and HaScheme, while the second
one could differ in exotic cases (like promises that return promises).
Instead of writing {{force}}, the operator {{!}} is used:

<enscript language="scheme">
(define (list-tail list n)
  (if (zero? n)
      list
      (list-tail (! (cdr list)) (- n 1))))
</enscript>

Now if one were to define {{!}} as the identity function in regular, call-by-value Scheme, then the block above will evaluate to the same value in both HaScheme and Scheme, in bounded space.

Ok, now we have fixed our space leak issues. Right? Let's try another
infinite list trick: a list of all natural numbers.

<enscript language="scheme">
(define naturals (list-tabulate +inf.0 (lambda (x) x)))
(! (list-tail naturals 1000000000))
</enscript>

This also leaks! This is because the promises are making new cons cells,
and storing them in {{naturals}}. We need to organize things to make sure
the program can clean up.

<enscript language="scheme">
(! (list-tail (list-tabulate +inf.0 (lambda (x) x)) 1000000000))
</enscript>

This will run in bounded space.

==== Call-by-Need and Conditionals

Since call-by-need will only execute a function when needed, conditional
forms like {{if}} can be implemented as functions and not syntax. In fact,
{{(hascheme control)}} implements {{if}}, {{and}}, {{or}}, and the {{cond}} as
functions, meaning one can pass them around as values.

For instance:

<enscript highlight="scheme">
(define (map f l)
  (cond
    ((null? l) '())
    ((pair? l) (cons (f (car l)) (cdr l)))
    (else (error "not a list" l))))
</enscript>

implemented with {{(hascheme control)}} is

<enscript highlight="scheme">
(define (map f l)
  (cond
   (null? l) '()
   (pair? l) (cons f (car l) (cdr l))
   #t (error "not a list" l)))
</enscript>

Neat, right? Well, if we go to {{list-tail}} we have a problem:

<enscript highlight="scheme">
(define (list-tail list n)
  (if (zero? n)
      list
      (list-tail (! (cdr list)) (- n 1))))
</enscript>

Since {{if}} is now a function, Scheme (our call-by-value host language)
will attempt to reduce {{(! (cdr list))}} every time, even when we don't
need to. We could go back to syntactic if, or we could add some wrapper
to the procedure. The {{seq}} function (named after the function in Haskell)
takes {{n}} forms, forces the first {{n-1}}, and returns the {{n}}th form.

<enscript highlight="scheme">
(define (list-tail list n)
  (if* (zero? n)
       list
       (seq (cdr list)
            (list-tail (cdr list) (- n 1)))))
</enscript>

==== Multiple Values and Continuations

HaScheme doesn't have {{call/cc}}. {{call/cc}} is not a function because it
does not return, so that's strike one for inclusion in a pure language.
Reified continuations make sense in a call-by-value language, because
there is a definite evaluation order (outermost first), but a lazy
language can execute any code at basically any time.

A future implementation might be able to use SRFI-226's delimited
control structures to implement continuations, because they are actual
functions.

Multiple values are specified as returning values to their continuation.
Since HaScheme does not (conceptually) have continuations, multiple
values have to be interpreted differently. But a bigger issue occurs
because a promise is a single value. It cannot be decomposed into more
values without forcing the promise.

=== Issues/Future Directions

* Lightly tested.
* I want to implement some purely functional data structures.

== Version History

; 0.2.0 : Added missing {{do}} form, misc. fixes, alot more tests, lists library, change license to 0BSD
; 0.1.0 : Initial Release

=== License

Copyright (C) Peter McGoron 2025

Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Some tests and support code (not used in the CHICKEN version) were adapted
from code written by André van Tonder.

Copyright (C) André van Tonder (2003). All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 DEALINGS IN THE SOFTWARE.