forked from arclanguage/anarki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arc.arc
2977 lines (2477 loc) · 79.6 KB
/
arc.arc
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
; Main Arc lib. Ported to Scheme version Jul 06.
; don't like names of conswhen and consif
; need better way of generating strings; too many calls to string
; maybe strings with escape char for evaluation
; make foo~bar equiv of foo:~bar (in expand-ssyntax)
; add sigs of ops defined in ac.scm
; get hold of error types within arc
; does macex have to be defined in scheme instead of using def below?
; write disp in arc
; could I get all of macros up into arc.arc?
; warn when shadow a global name
; some simple regexp/parsing plan
; compromises in this implementation:
; no objs in code
; (mac testlit args (listtab args)) breaks when called
; separate string type
; (= (cdr (cdr str)) "foo") couldn't work because no way to get str tail
; not sure this is a mistake; strings may be subtly different from
; lists of chars
(assign incompatibilities (fn () (disp
"The following behave differently from arc 3.1:
1. `for`. See (help for).
2. Templates (arc's lightweight object database system). See (help deftem).
If you find others, please report them at http://arclanguage.org/forum.
")))
(assign current-load-file* "arc.arc")
(assign source-file* (table))
(assign source* (table))
(assign help* (table))
(assign remac (annotate 'mac
(fn (name parms . body)
; remac doesn't actually make the help text available
; but adding it won't do any harm
`(assign ,name (annotate 'mac (fn ,parms ,@body))))))
(remac document (definer name parms doc . body)
`((fn ()
(sref sig* ',parms ',name)
(sref help* ,doc ',name) ; doc will be a literal string
(sref source-file* current-load-file* ',name)
(sref source* '(,definer ,name ,parms ,@body) ',name))))
(document builtin fn (params . body)
"Creates an anonymous function. See the tutorial: http://ycombinator.com/arc/tut.txt")
(document builtin apply (f . args)
"(apply f '(1 2 3)) <=> (f 1 2 3)
(apply f x y '(z w)) <=> (f x y z w)")
(document builtin annotate (tag . val)
"Creates a user-defined tagged type containing 'val'. See also [[type]] and [[rep]].")
(document builtin type (x)
"Returns the type of 'x', even if 'x' is a user-defined tagged-type.")
(document builtin rep (x)
"Returns the contents of a user-defined tagged type object.")
(document builtin assign (x y)
"Set variable 'x' to value 'y'.")
(document builtin bound (x)
"Does variable 'x' currently have a value?")
(remac warn-if-bound (var)
`(if (bound ',var)
((fn () (disp "*** redefining " (stderr))
(disp ',var (stderr))
(disp #\newline (stderr))))))
(remac mac (name parms . body)
"Defines a new *macro*, or abbreviation for some more complex code.
Macros are the hallmark of lisp, the ability to program on programs.
For more information see the tutorial: http://ycombinator.com/arc/tut.txt
Or come ask questions at http://arclanguage.org/forum"
`((fn () (warn-if-bound ,name)
(document mac ,name ,parms
,@(if (is (type car.body) 'string)
body
(cons nil body)))
(remac ,name ,parms ,@body))))
(assign examples* (table))
(mac examples (name . tests-and-expected-results)
"Shows some example calls of a function as an enhancement of its docstring.
Usually provided immediately after a function docstring+definition, so it
isn't underfoot when it isn't needed.
Usage: (examples name-being-tested
expr1
expected-result1
expr2
expected-result2
...)
Expected results are optional. When provided, they can remind you when
documentation goes out of date. To avoid printing and checking them, use an _
wildcard. For example:
(examples foo
(foo x)
_
(foo y z)
_)
Expected results are compared directly, without evaluation. For example:
(def foo (a b c)
(list a b c))
(examples foo
(foo 1 2 3)
(1 2 3)) <-- no quote
If the result is an object that read can't handle, use valueof. For example:
(examples foo
(foo x)
(valueof (obj a x)))"
`(sref examples* ',tests-and-expected-results ',name))
(examples assign
(assign x 10)
_)
(examples bound
(do (= y 10)
(bound 'y))
t)
(mac do args
"Evaluates each expression in sequence and returns the result of the
last expression."
`((fn () ,@args)))
(examples do
(do (prn "line 1")
(prn "line 2")
(prn "line 3"))
_)
(mac def (name parms . body)
"Defines a new function called 'name'. When called, the function runs
'body', parameterizing 'parms' with call arguments.
For more information see the tutorial: http://ycombinator.com/arc/tut.txt
Or come ask questions at http://arclanguage.org/forum"
`(do (warn-if-bound ,name)
(document def ,name ,parms
,@(if (is (type car.body) 'string)
body
(cons nil body)))
(assign ,name (fn ,parms ,@body))))
(mac redef (name parms . body)
"Defines a new function like [[def]], but doesn't warn if 'name' already exists."
`(do (if (~help* ',name) ; assume any existing help is still accurate
(document redef ,name ,parms
,@(if (is (type car.body) 'string)
body
(cons nil body))))
(assign ,name (fn ,parms ,@body))))
(document builtin cons (x xs) "Returns a new list with element 'x' added to the start of list 'xs'.")
(document builtin car (xs) "Returns the first element of list 'xs'")
(document builtin cdr (xs) "Returns all elements of list 'xs' but the first")
(def caar (xs)
"Equivalent to (car (car xs))"
(car:car xs))
(def cadr (xs)
"Equivalent to (car (cdr xs)). Returns the second element of the list 'xs'"
(car:cdr xs))
(def cddr (xs)
"Equivalent to (cdr (cdr xs)). Returns all elements of list 'xs' but the first two."
(cdr:cdr xs))
(def cdar (xs)
"Equivalent to (cdr (car xs))."
(cdr:car xs))
(def cadar (xs)
"Equivalent to (car (cdar xs))."
(car:cdar xs))
(def no (x)
"Is 'x' nil? Sometimes we say A passes if it's non-nil, in which case no.A is said to fail."
(is x nil))
(def acons (x)
"Is 'x' a non-nil list?"
(is type.x 'cons))
; Can return to this def once Rtm gets ac to make all rest args
; nil-terminated lists.
; (def list args args)
(def list args
"Creates a list containing the given 'args'."
(if no.args
nil
(cons car.args
(apply list cdr.args))))
(examples list
(list 1 2 3)
(1 2 3)
(list "a" '(1 2) 3)
("a" (1 2) 3))
(document def len (x)
"Computes the size of a list, string, hash table or other user-defined type.")
(examples len
(len '(1 2 3))
3
(len "abcd")
4
(len (obj a 1 b 2))
2)
(def idfn (x)
"The identity function. Returns whatever is passed in."
x)
(def map1 (f xs)
"Returns a list containing the result of function 'f' applied to every element of 'xs'."
(if (no xs)
nil
(cons (f car.xs)
(map1 f cdr.xs))))
(examples map1
(map1 cdr '((1) (2 3) (4 5)))
(nil (3) (5))
(map1 [list _ (* _ 10)]
'(1 2 3))
((1 10) (2 20) (3 30)))
(def pair (xs (o f list))
"Splits the elements of 'xs' into buckets of two, and optionally applies the
function 'f' to them."
(if (no xs)
nil
(no cdr.xs)
(list (list car.xs))
(cons (f car.xs cadr.xs)
(pair cddr.xs f))))
(examples pair
(pair '(a b c d))
((a b) (c d))
(pair '(a b c d e))
((a b) (c d) (e))
(pair '(1 2 3 4) +)
(3 7)
(pair '(10 2 3 40 50 6) max)
(10 40 50))
(mac make-br-fn (body)
"The function invoked on square-bracket calls.
For example, [car _] => (make-br-fn (car _)) => (fn (_) (car _))"
`(fn (_) ,body))
(mac and args
"Stops at the first argument to fail (return nil). Returns the last argument before stopping."
(if args
(if (cdr args)
`(if ,(car args) (and ,@(cdr args)))
(car args))
t))
(def assoc (key al)
"Finds a (key value) pair in an association list 'al' of such pairs."
(if (no acons.al)
nil
(and (acons (car al)) (is (caar al) key))
(car al)
(assoc key (cdr al))))
(def alref (al key)
"Returns the value of 'key' in an association list 'al' of (key value) pairs"
(cadr (assoc key al)))
(mac with (parms . body)
"Evaluates all expressions in 'body' under the bindings provided in 'parms'.
Returns value of last expression in 'body'.
For example, (with (x 1 y 2)
(+ x y))
=> 3"
`((fn ,(map1 car (pair parms))
,@body)
,@(map1 cadr (pair parms))))
(mac let (var val . body)
"Like [[with]] but with just one binding.
For example, (let x 1
(+ x 1))
=> (with (x 1)
(+ x 1))
=> 2"
`(with (,var ,val) ,@body))
(mac withs (parms . body)
"Like [[with]], but binding for a variable can refer to earlier variables.
For example, (withs (x 1 y (+ x 1))
(+ x y))
=> 3"
(if (no parms)
`(do ,@body)
`(let ,(car parms) ,(cadr parms)
(withs ,(cddr parms) ,@body))))
(mac ret (var val . body)
"Like [[let]], but returns 'val' rather than the value of the final form in 'body'."
`(let ,var ,val ,@body ,var))
(mac w/uniq (names . body)
"Assigns a set of variables to unique symbols.
Useful for avoiding name capture in macros; see the tutorial: http://ycombinator.com/arc/tut.txt"
(if (acons names)
`(with ,(apply + nil (map1 (fn (n) `(,n (uniq ',n)))
names))
,@body)
`(let ,names (uniq ',names) ,@body)))
(mac do1 args
"Like [[do]], but returns the value of the first arg rather than the last."
(w/uniq g
`(ret ,g ,(car args)
,@(cdr args))))
(mac defextend (name args pred . body)
"Extends an existing function to trigger only if 'pred' is non-nil."
(w/uniq (old allargs)
`(let ,old ,name
(redef ,name ,allargs
(let ,args ,allargs
(if ,pred
(do ,@body)
(apply ,old ,allargs))))
(sref sig* ',args ',name))))
; Rtm prefers to overload + to do this
(def join args
"Concatenates/appends its arguments into a new list."
(if (no args)
nil
(let a (car args)
(if (no a)
(apply join (cdr args))
(cons (car a) (apply join (cdr a) (cdr args)))))))
(examples join
(join '(1 2) nil '(3 4))
(1 2 3 4))
(mac rfn (name parms . body)
"Like [[fn]] but permits the created function to call itself recursively as the given 'name'."
`(let ,name nil
(assign ,name (fn ,parms ,@body))))
(mac afn (parms . body)
"Like [[fn]] and [[rfn]] but the created function can call itself as 'self'"
`(let self nil
(assign self (fn ,parms ,@body))))
(examples afn
((afn (x) ; powers of two
(if (is x 0)
1
(* 2 (self (- x 1)))))
5)
32)
; a more readable variant of afn
; http://awwx.ws/xloop0; http://arclanguage.org/item?id=10055
(mac loop (withses . body)
"Like 'with', but the body can also be rerun with new bindings by calling 'recur'.
Often a more readable alternative to [[rfn]] or [[afn]].
For example, this prints numbers ad infinitum:
(loop (x 1)
(prn x)
(recur (+ x 1)))"
(let w pair.withses
`((rfn recur ,(map1 car w) ,@body)
,@(map1 cadr w))))
(mac point (name . body)
"Like [[do]], but may be exited by calling 'name' from within 'body'."
(w/uniq (g p)
`(ccc (fn (,g)
(let ,name (fn ((o ,p)) (,g ,p))
,@body)))))
; Ac expands x:y:z into (compose x y z)
; The last arg (z above) cannot be a macro unless the form is in functional
; position.
;
; Composes in functional position are transformed away by ac.
(mac compose args
"Takes a list of functions and returns a function that behaves as if all its
'args' were called in sequence.
For example, this is always true:
((compose f g h) a b c) <=> (f (g (h a b c))).
Be wary of passing macros to compose."
(w/uniq g
`(fn ,g
,(loop (fs args)
(if cdr.fs
(list car.fs (recur cdr.fs))
`(apply ,(if car.fs car.fs 'idfn) ,g))))))
; Ac expands ~x into (complement x)
; x cannot be a macro unless the form is in functional position.
; Complement in functional position is transformed away by ac, and can handle
; macros.
(def complement (f)
"Returns a function that behaves as if the result of calling 'f' was negated.
For example, this is always true:
((complement f) a b) <=> (no (f a b))"
(fn args (no (apply f args))))
(def rev (xs)
"Returns a list containing the elements of 'xs' back to front."
(loop (xs xs acc nil)
(if (no xs)
acc
(recur cdr.xs
(cons car.xs acc)))))
(examples rev
(rev '(1 (2 3) 4))
(4 (2 3) 1))
(def isnt (x y) (no (is x y)))
(mac or args
"Stops at the first argument to pass, and returns its result."
(and args
(w/uniq g
`(let ,g ,car.args
(if ,g ,g
(or ,@cdr.args))))))
(def alist (x)
"Is 'x' a (possibly empty) list?"
(or no.x acons.x))
(mac in (x . choices)
"Does 'x' match one of the given 'choices'?"
(w/uniq g
`(let ,g ,x
(or ,@(map1 (fn (c) `(is ,g ,c))
choices)))))
(def atom (x)
"Is 'x' a simple type? (i.e. not list, table or user-defined)"
(in type.x 'int 'num 'sym 'char 'string))
(document builtin is (x y)
"Are 'x' and 'y' identical?")
(def iso (x y)
"Are 'x' and 'y' equal-looking to each other? Non-atoms like lists and tables can contain
the same elements (be *isomorphic*) without being identical."
(or (is x y)
(and (acons x)
(acons y)
(iso (car x) (car y))
(iso (cdr x) (cdr y)))))
(document builtin if (test1 then1 test2 then2 ... else)
"Version 1: (if test then) runs 'then' if 'test' passes.
Version 2: (if test then else) runs 'then' or 'else' depending on whether
'test' passes or fails.
Version 3: takes arbitrary numbers of alternating tests and expressions,
running the first expression whose test passes. Optionally might take an
'else' branch to run if none of the tests pass.")
(mac when (test . body)
"Like [[if]], but can take multiple expressions to run when 'test' is not nil.
Can't take an 'else' branch."
`(if ,test (do ,@body)))
(mac unless (test . body)
"Opposite of [[when]]; runs multiple expressions when 'test' is nil."
`(if (no ,test) (do ,@body)))
(def reclist (f xs)
"Calls function 'f' with successive [[cdr]]s of 'xs' until one of the calls passes."
(and xs (or (f xs) (if (acons xs) (reclist f (cdr xs))))))
(examples reclist
(reclist [caris _ 'b] '(a b c))
t
(reclist [caris _ 'd] '(a b c))
nil
(reclist [if (is 2 len._) _] '(a b c d))
(c d))
(def recstring (test s (o start 0))
"Calls function 'test' with successive characters in string 's' until one of the calls passes."
(loop (i start)
(and (< i len.s)
(or test.i
(recur (+ i 1))))))
(def testify (x)
"Turns an arbitrary value 'x' into a predicate function to compare with 'x'."
(if (isa x 'fn) x [iso _ x]))
(def carif (x)
"Returns the first element of the given list 'x', or just 'x' if it isn't a list."
(on-err (fn(_) x)
(fn() (car x))))
(examples carif
(carif '(1 2))
1
(carif 3)
3)
(def some (test seq)
"Does at least one element of 'seq' satisfy 'test'?"
(let f testify.test
(reclist f:carif seq)))
(defextend some (test seq) (isa seq 'string)
(let f testify.test
(recstring f:seq seq)))
(def all (test seq)
"Does every element of 'seq' satisfy 'test'?"
(~some (complement (testify test)) seq))
(mac check (x test (o alt))
"Returns `x' if it satisfies `test', otherwise returns 'alt' (nil if it's not provided)."
(w/uniq gx
`(let ,gx ,x
(if (,test ,gx) ,gx ,alt))))
(mac acheck (x test (o alt))
"Like [[check]], but 'alt' can refer to the value of expr 'x' as 'it.
Pronounced 'anaphoric check'."
`(let it ,x
(if (,test it)
it
,alt)))
(def find (test seq)
"Returns the first element of 'seq' that satisfies `test'."
(let f testify.test
(reclist [check carif._ f] seq)))
(examples find
(find 3 '(1 2 3 4))
3
(find odd '(1 2 3 4))
1
(find odd '(2 4 6))
nil)
(defextend find (test seq) (isa seq 'string)
(let f testify.test
(recstring [check seq._ f] seq)))
(def mem (test seq)
"Returns suffix of 'seq' after the first element to satisfy 'test'.
This is the most reliable way to check for presence, even when searching for nil."
(let f (testify test)
(reclist [if (f:carif _) _] seq)))
(examples mem
(mem odd '(2 4 5 6 7))
(5 6 7)
(mem 6 '(2 4 5 6 7))
(6 7))
(def isa (x y)
"Is 'x' of type 'y'?"
(is (type x) y))
(document builtin coerce (x type)
"Try to turn 'x' into a value of a different 'type'.")
(mac as (type expr)
"Tries to convert 'expr' into a different 'type'.
More convenient form of [[coerce]] with arguments reversed; doesn't need
'type' to be quoted."
`(coerce ,expr ',type))
(def sym (x)
"Converts 'x' into a symbol."
(coerce x 'sym))
(def int (x (o b 10))
"Converts 'x' into an integer, optionally in the given base 'b' (decimal by default)."
(coerce x 'int b))
(def real (x)
"Converts 'x' into a real number."
($.exact->inexact x))
(def string args
"Converts all 'args' into strings and concatenate the result."
(apply + "" (map [coerce _ 'string] args)))
; Possible to write map without map1, but makes News 3x slower.
;(def map (f . seqs)
; (if (some1 no seqs)
; nil
; (no (cdr seqs))
; (let s1 (car seqs)
; (cons (f (car s1))
; (map f (cdr s1))))
; (cons (apply f (map car seqs))
; (apply map f (map cdr seqs)))))
(def map (f . seqs)
"Successively applies corresponding elements of 'seqs' to function 'f'.
Generalizes [[map1]] to functions with more than one argument."
(if (no cdr.seqs)
(map1 f car.seqs)
(all idfn seqs)
(cons (apply f (map1 car seqs))
(apply map f (map1 cdr seqs)))))
(defextend map (f . seqs) (some [isa _ 'string] seqs)
(withs (n (apply min (map1 len seqs))
new (newstring n))
(loop (i 0)
(if (is i n)
new
(do (sref new (apply f (map1 [_ i] seqs)) i)
(recur (+ i 1)))))))
(examples map
(map cdr '((1) (2 3) (4 5)))
(nil (3) (5))
(map [list _ (* _ 10)]
'(1 2 3))
((1 10) (2 20) (3 30))
(map + '(1 2 3) '(4 5 6))
(5 7 9)
(map (fn (c n) (coerce (+ n (coerce c 'int)) 'char)) "abc" '(0 2 4))
"adg"
(map min "bird" "elephant")
"bied")
; common uses of map
(def mappend (f . args)
"Like [[map]] followed by append."
(apply + nil (apply map f args)))
(examples mappend
(mappend cdr '((1) (2 3) (4 5)))
(3 5)
(mappend [list _ (* _ 10)] '(1 2 3))
(1 10 2 20 3 30))
(def subst (old new seq)
"Returns a copy of 'seq' with all values of 'old' replaced with 'new'."
(map (fn (_)
(if (testify.old _)
(if (isa new 'fn) new._ new)
_))
seq))
(def firstn (n xs)
"Returns the first 'n' elements of 'xs'."
(if (no n) xs
(and (> n 0) xs) (cons (car xs) (firstn (- n 1) (cdr xs)))
nil))
(examples firstn
(firstn 3 '(1 2))
(1 2)
(firstn 3 '(a b c d e))
(a b c))
(def lastn (n xs)
"Returns the last 'n' elements of 'xs'."
(rev:firstn n rev.xs))
(def nthcdr (n xs)
"Returns all but the first 'n' elements of 'xs'."
(if (no n) xs
(> n 0) (nthcdr (- n 1) (cdr xs))
xs))
(examples nthcdr
(nthcdr 0 '(1 2 3))
(1 2 3)
(nthcdr 1 '(1 2 3))
(2 3)
(nthcdr 2 '(1 2 3))
(3)
(nthcdr 10 '(1 2 3))
nil)
(def lastcons (xs)
"Returns the absolute last link of list 'xs'. Save this value to efficiently
append to 'xs'."
(if cdr.xs
(lastcons cdr.xs)
xs))
; Generalization of pair: (tuples x) = (pair x)
(def tuples (xs (o n 2))
"Splits 'xs' up into lists of size 'n'. Generalization of [[pair]]."
(if (no xs)
nil
(cons (firstn n xs)
(tuples (nthcdr n xs) n))))
(examples tuples
(tuples '(1 2 3 4 5) 1)
((1) (2) (3) (4) (5))
(tuples '(1 2 3 4 5) 2)
((1 2) (3 4) (5))
(tuples '(1 2 3 4 5) 3)
((1 2 3) (4 5)))
; If ok to do with =, why not with def? But see if use it.
(mac defs args
`(do ,@(map [cons 'def _] (tuples args 3))))
(def caris (x val)
(and (acons x) (is (car x) val)))
(examples caris
(caris '(1 2) 1)
t
(caris 1 1)
nil)
(def warn (msg . args)
"Displays args to screen as a warning."
(disp (+ "Warning: " msg ". "))
(map [do (write _) (disp " ")] args)
(disp #\newline))
(mac atomic body
"Runs expressions in 'body' with exclusive access to system resources.
Currently invoked for you anytime you modify a variable. This can slow things down, but
prevents multiple threads of execution from stepping on each other's toes by, say,
writing to a variable at the same time."
`(atomic-invoke (fn () ,@body)))
(mac atlet args
"Like [[let]], but [[atomic]]."
`(atomic (let ,@args)))
(mac atwith args
"Like [[with]], but [[atomic]]."
`(atomic (with ,@args)))
(mac atwiths args
"Like [[withs]], but [[atomic]]."
`(atomic (withs ,@args)))
(document builtin sref (aggregate value . indices)
"Sets position 'indices' in 'aggregate' (which might be a list, string, hash
table, or other user-defined type) to 'value'.")
(examples sref
(ret x '(1 2 3)
(sref x 4 1))
(1 4 3)
(ret x "abc"
(sref x #\d 0))
"dbc"
(ret x (obj a 1 b 2)
(sref x 3 'd))
(valueof (obj a 1 b 2 d 3)))
; setforms returns (vars get set) for a place based on car of an expr
; vars is a list of gensyms alternating with expressions whose vals they
; should be bound to, suitable for use as first arg to withs
; get is an expression returning the current value in the place
; set is an expression representing a function of one argument
; that stores a new value in the place
; A bit gross that it works based on the *name* in the car, but maybe
; wrong to worry. Macros live in expression land.
; seems meaningful to e.g. (push 1 (pop x)) if (car x) is a cons.
; can't in cl though. could I define a setter for push or pop?
(assign setter (table))
(mac defset (name parms . body)
(w/uniq gexpr
`(sref setter
(fn (,gexpr)
(let ,parms (cdr ,gexpr)
,@body))
',name)))
(defset car (x)
(w/uniq g
(list (list g x)
`(car ,g)
`(fn (val) (scar ,g val)))))
(defset cdr (x)
(w/uniq g
(list (list g x)
`(cdr ,g)
`(fn (val) (scdr ,g val)))))
(defset caar (x)
(w/uniq g
(list (list g x)
`(caar ,g)
`(fn (val) (scar (car ,g) val)))))
(defset cadr (x)
(w/uniq g
(list (list g x)
`(cadr ,g)
`(fn (val) (scar (cdr ,g) val)))))
(defset cddr (x)
(w/uniq g
(list (list g x)
`(cddr ,g)
`(fn (val) (scdr (cdr ,g) val)))))
; Note: if expr0 macroexpands into any expression whose car doesn't
; have a setter, setforms assumes it's a data structure in functional
; position. Such bugs will be seen only when the code is executed, when
; sref complains it can't set a reference to a function.
(def setforms (expr0)
(let expr (macex expr0)
(if (isa expr 'sym)
(if (ssyntax expr)
(setforms (ssexpand expr))
(w/uniq (g h)
(list (list g expr)
g
`(fn (,h) (assign ,expr ,h)))))
; make it also work for uncompressed calls to compose
(and (acons expr) (metafn (car expr)))
(setforms (expand-metafn-call (ssexpand (car expr)) (cdr expr)))
(and (acons expr) (acons (car expr)) (is (caar expr) 'get))
(setforms (list (cadr expr) (cadr (car expr))))
(let f (setter (car expr))
(if f
(f expr)
; assumed to be data structure in fn position
(do (when (caris (car expr) 'fn)
(warn "Inverting what looks like a function call"
expr0 expr))
(w/uniq (g h)
(let argsyms (map [uniq] (cdr expr))
(list (+ (list g (car expr))
(mappend list argsyms (cdr expr)))
`(,g ,@argsyms)
`(fn (,h) (sref ,g ,h ,(car argsyms))))))))))))
(def metafn (x)
(or (ssyntax x)
(and (acons x) (in (car x) 'compose 'complement))))
(def expand-metafn-call (f args)
(if (is (car f) 'compose)
(loop (fs cdr.f)
(if (caris car.fs 'compose) ; nested compose
(recur (join cdar.fs cdr.fs))
(cdr fs)
(list car.fs (recur cdr.fs))
:else
(cons car.fs args)))
(is (car f) 'no)
(err "Can't invert " (cons f args))
:else
(cons f args)))
(def expand= (place val)
(if (and (isa place 'sym) (~ssyntax place))
`(assign ,place ,val)
(let (vars prev setter) (setforms place)
(w/uniq g
`(atwith ,(+ vars (list g val))
(,setter ,g))))))
(def expand=list (terms)
`(do ,@(map (fn ((p v)) (expand= p v)) ; [apply expand= _]
(pair terms))))
(mac = args
"(= var val) saves 'val' in 'var'.
(= var1 val1 var2 val2) saves 'val's in corresponding 'var's.
'var's can be complex expressions like (car x), and so on. See [[defset]].
When you run multiple threads at once, only one will ever be modifying a variable at once.
See [[atomic]]."
(expand=list args))
(examples =
(= x 1)
_
(= x 2 y 4)
_)
; http://arclanguage.org/item?id=12229
(mac for (var init test update . body)
"Loops through expressions in 'body' as long as 'test' passes, first binding 'var' to 'init'. At the end of each iteration it runs 'update', which usually will modify 'var'.
Can also be terminated from inside 'body' by calling '(break)', or interrupt a single iteration by calling '(continue)'.
If you nest multiple loops with different 'var's like i and j, you can break out of either of them by calling (break-i), (break-j), etc.
Always returns nil.
Incompatibility alert: 'for' is different in anarki from vanilla arc. To get vanilla arc's behavior, use [[up]]. For more information, see CHANGES/for."
; simple heuristic to alert on the incompatibility at call time. If you need
; to check a flag variable you should probably be using 'while' anyway.
(unless (acons test)
(err "`for` has changed in anarki. See (help for) for more information."))
`(point break
(let ,(sym:string "break-" var) break
(loop (,var ,init)
(when ,test
(do1 nil
(point continue
(let ,(sym:string "continue-" var) continue
,@body))
,update
,(if (acons var)
`(recur (list ,@var))
`(recur ,var))))))))
(mac up (v init max . body)
"Counts 'v' up from 'init' (inclusive) to 'max' (exclusive), running 'body'
with each value. Can also (break) and (continue) inside 'body'; see [[for]]."
`(for ,v ,init (< ,v ,max) (assign ,v (+ ,v 1))
,@body))
(mac down (v init min . body)
"Counts 'v' down from 'init' (inclusive) to 'min' (exclusive), running 'body'
with each value. Can also (break) and (continue) inside 'body'; see [[for]]."
`(for ,v ,init (> ,v ,min) (assign ,v (- ,v 1))
,@body))
(mac repeat (n . body)
"Runs 'body' expression by expression 'n' times."
(w/uniq gi
`(up ,gi 0 ,n
,@body)))
(mac forlen (var s . body)
"Loops through the length of sequence 's', binding each element to 'var'."
`(up ,var 0 (len ,s)
,@body))
(def walk (seq f)
"Calls function 'f' on each element of 'seq'. See also [[map]]."
(loop (l seq)
(when acons.l
(f car.l)
(recur cdr.l))))
(mac each (var expr . body)
"Loops through expressions in 'body' with 'var' bound to each successive
element of 'expr'."
`(walk ,expr (fn (,var) ,@body)))
(defextend walk (seq f) (isa seq 'table)
(maptable (fn (k v)
(f (list k v)))
seq))
(defextend walk (seq f) (isa seq 'string)
(forlen i seq
(f seq.i)))
; ; old definition of 'each. possibly faster, but not extendable.
; (mac each (var expr . body)
; (w/uniq (gseq gf gv)
; `(let ,gseq ,expr
; (if (alist ,gseq)
; ((rfn ,gf (,gv)
; (when (acons ,gv)
; (let ,var (car ,gv) ,@body)
; (,gf (cdr ,gv))))
; ,gseq)
; (isa ,gseq 'table)