Merge pull request #174 from dubek/issue_166_schemes
[jackhill/mal.git] / racket / core.rkt
CommitLineData
f5223195
JM
1#lang racket
2
3(provide core_ns)
4
5(require "readline.rkt" "types.rkt" "reader.rkt" "printer.rkt")
6
7(define (throw exc)
8 (raise (make-mal-exn "mal exception"
9 (current-continuation-marks)
10 exc)))
11
12;; Sequence functions
20c05e35
JM
13(define do_apply
14 (lambda a
15 (let* ([f (first a)]
16 [lst (_to_list (last a))]
17 [args (append (take (drop a 1) (- (length a) 2)) lst)])
18 (apply f args))))
19
f5223195
JM
20(define conj
21 (lambda a
22 (if (vector? (first a))
23 (vector-append (first a) (list->vector (rest a)))
24 (append (reverse (rest a)) (first a)))))
25
b8c4d052
DM
26(define (seq obj)
27 (cond [(_nil? obj) nil]
28 [(_string? obj) (if (eq? 0 (string-length obj)) nil (map string (string->list obj)))]
29 [(_empty? obj) nil]
30 [else (_to_list obj)]))
31
f5223195
JM
32;; Meta functions
33(define (meta obj)
34 (cond [(malfunc? obj) (malfunc-meta obj)]
35 [else nil]))
36
37(define (with-meta obj m)
38 (cond [(malfunc? obj) (struct-copy malfunc obj [meta m])]
39 [else (raise "metadata not supported on type")]))
40
41;; Atom functions
42
43(define swap!
44 (lambda a
45 (let* ([atm (first a)]
46 [f (second a)]
47 [args (cons (atom-val atm) (rest (rest a)))]
48 [val (apply f args)])
49 (set-atom-val! atm val)
50 val)))
51
52(define core_ns
53 (hash
54 '= _equal?
55 'throw throw
56
57 'nil? _nil?
58 'true? (lambda (x) (eq? x #t))
59 'false? (lambda (x) (eq? x #f))
60 'symbol (lambda (s) (if (symbol? s) s (string->symbol s)))
61 'symbol? symbol?
b8c4d052 62 'string? _string?
f5223195
JM
63 'keyword (lambda (s) (if (_keyword? s) s (_keyword s)))
64 'keyword? _keyword?
65
66 'pr-str (lambda a (pr_lst a #t " "))
67 'str (lambda a (pr_lst a #f ""))
68 'prn (lambda a (printf "~a~n" (pr_lst a #t " ")) nil)
69 'println (lambda a (printf "~a~n" (pr_lst a #f " ")) nil)
70 'read-string (lambda (s) (read_str s))
71 'readline readline
72 'slurp (lambda (f) (port->string (open-input-file f)))
73
74 '< <
75 '<= <=
76 '> >
77 '>= >=
78 '+ +
79 '- -
80 '* *
81 '/ /
82 'time-ms (lambda () (round (current-inexact-milliseconds)))
83
84 'list list
85 'list? list?
86 'vector vector
87 'vector? vector?
88 'hash-map hash
89 'map? hash?
90 'assoc _assoc
91 'dissoc _dissoc
92 'get _get
93 'contains? dict-has-key?
94 'keys hash-keys
95 'vals hash-values
96
97 'sequential? _sequential?
98 'cons (lambda a (cons (first a) (_to_list (second a))))
99 'concat (lambda a (apply append (map _to_list a)))
100 'nth _nth
101 'first _first
102 'rest _rest
103 'empty? _empty?
104 'count _count
20c05e35 105 'apply do_apply
f5223195
JM
106 'map (lambda (f s) (_to_list (_map f s)))
107 'conj conj
b8c4d052 108 'seq seq
f5223195
JM
109
110 'meta meta
111 'with-meta with-meta
112 'atom atom
113 'atom? atom?
114 'deref (lambda (a) (atom-val a))
115 'reset! (lambda (a v) (set-atom-val! a v) v)
116 'swap! swap!))