forked from alex-eg/sex
A match binder looks like a reference to its field and is not one. And with `.' reading an untyped receiver as a value, nothing said how to write the arrow by hand.
47 lines
1.3 KiB
Scheme
47 lines
1.3 KiB
Scheme
(input)
|
|
(output "-(2 + 3)"
|
|
"-5")
|
|
(return 0)
|
|
|
|
;;; The worked example from Encapsulation.org, kept here so it stays
|
|
;;; true: a recursive sum, an inherent method on it, and a spec
|
|
;;; realized for it, which is every layer that is built at once.
|
|
|
|
(include stdio.h)
|
|
|
|
(sum expr
|
|
((lit ((v float)))
|
|
(neg ((e (* const expr))))
|
|
(add ((l (* const expr)) (r (* const expr))))))
|
|
|
|
(ops expr
|
|
(pub fn eval ((self (* const expr))) float
|
|
;; v, e, l and r are copies of the fields, not references to them
|
|
(match (* self)
|
|
((lit (v)) (return v))
|
|
((neg (e)) (return (- (.eval e))))
|
|
((add (l r)) (return (+ (.eval l) (.eval r)))))))
|
|
|
|
(spec (printable T)
|
|
(fn show ((self (* const T))) void)
|
|
(fn show-line ((self (* const T))) void ; default, calls the required one
|
|
(.show self)
|
|
(printf "\n")))
|
|
|
|
(realize (printable expr)
|
|
(fn show ((self (* const expr))) void
|
|
(match (* self)
|
|
((lit (v)) (printf "%g" v))
|
|
((neg (e)) (printf "-") (.show e))
|
|
((add (l r)) (printf "(") (.show l) (printf " + ") (.show r) (printf ")")))))
|
|
|
|
(pub fn main () int
|
|
(var two expr (expr/lit 2.0))
|
|
(var three expr (expr/lit 3.0))
|
|
(var both expr (expr/add (& two) (& three)))
|
|
(var e expr (expr/neg (& both)))
|
|
|
|
(.show-line e) ; -(2 + 3)
|
|
(printf "%g\n" (.eval e)) ; -5
|
|
(return 0))
|