forked from clojerl/clojerl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeftype.clje
66 lines (52 loc) · 1.4 KB
/
deftype.clje
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
(ns examples.deftype
(:require [examples.protocols :as other]))
(deftype SomeType [value1 value2]
clojerl.IHash
(hash [_] 42)
clojerl.IStringable
(str [_]
(str "#SomeType[value1 = " value1 ", value2 = " value2 "]")))
(let [x (new SomeType 1 2)]
(prn x)
(prn (.hash x)))
(defrecord SomeRecord [x y]
clojerl.IHash
(hash [this] (+ x y)))
(let [x (new SomeRecord 1 2)]
(prn x)
(prn (.hash x))
(prn (:x x))
(prn (assoc x :x 42 :z *out*))
(prn (merge x {:y 1984 :z :keyword}))
(prn (merge {:y 1984 :z :keyword} x))
(prn (= {:x 1 :y 2} x)))
(defprotocol SomeProtocol
(function-one [this] [this a])
(function-two [this a b c]))
(defprotocol OtherProtocol
(foo [this])
(bar [this]))
(extend-type SomeRecord
SomeProtocol
(function-one [this] :one)
(function-one [this a] [:one a])
(function-two [this a b c] #{:one a b c})
examples.deftype.OtherProtocol
(foo [this] {:foo (:y this)})
(bar [this] {:bar (:x this)}))
(prn (foo (new SomeRecord 1 2)))
(prn (bar (new SomeRecord 1 2)))
(extend-type default
clojerl.IStringable
(str [this]
(erlang/iolist_to_binary
(io_lib/format #erl"~p" #erl(this)))))
(deftype NonStringable [])
(prn (str (NonStringable.)))
other/ExampleProtocol
(prn #examples.deftype.SomeRecord{:x 1 :y 2})
(prn #examples.deftype.SomeRecord[1 2])
(prn (SomeRecord/create {:x 1 :y 2}))
(deftype Foo []
clojerl.IStringable
(str [_] (str Foo)))