r2/test.tng
author Tony Garnock-Jones <tonygarnockjones@gmail.com>
Wed, 16 Jan 2019 17:15:58 +0000
changeset 438 1fe179d53161
parent 32 6c53aceebafd
permissions -rw-r--r--
Add missing primitive implementation for the plain interpreter.

define map [
  f: [Nil           : Nil
      [Hd: h Tl: t] : [Hd: f h Tl: map f t]]
];;

(arg Hd)
(arg Tl)

"a pattern:" [(a b): _]
"-->" (arg a b)

define fold-left [
  kons: [knil: [Nil           : knil
                [Hd: h Tl: t] : fold-left kons (kons h knil) t]]
];;

map [x: x + 1] ([1, 2, 3] AsList);;

letrec (map = [f: [Nil            : Nil
	           [Hd: h Tl: t]) : [Hd: f h Tl: map f t]],
	toList = [[]     : Nil
		  [h ; t]: [Hd: h Tl: (toList t)]]); "yikes"
map [x: x] (toList [1 2 3])
;;

map [x: x + 1] (toList [1 2 3]);;

[x: (Update: [] Set: x To: 123)] 'hi';;

define-behaviour Cst;;
define-method ({Cst cst} Convert) (
  Case: {cst} Of: (
    [[Adj: [l, r]]: [(l Convert) (r Convert)]],
    [[Tuple: cs]: (let cs* = map [x: x Convert] cs in {Tuple cs*})],
    [[Quote: v]: v],
    [_: cst]
  )
);;

"To lift something:" {lifted} <- val
"To drop something:" val <- {lifted}

define-method ({Tuple x} Length) (
  x Length;;
);;

define-method ({Tuple x} AsList) (
  (0 .. x Length) Map: [i: x ? i]
);;

"A semi- or pseudo-monadic version:"
define-method ((results = {ParseResults _}) Next) (
  [has-value, next] <- (atomic Read: (results Next*)),
  (If: has-value
   Then: next
   Else: (next-value <- (next []),
	  atomic Into: (results Next*) Write: (True, next-value),
	  next-value))
);;

"A monadic version:"
"(This is stupid code anyway because it's a lazy language,
it already delays and evaluates once!)"
"We don't put the 'atomic' in here to stay compositional as long as possible"
define-method ((results = {ParseResults _}) Next) (
  [has-value, next] <- (Read: (results Next*)),
  (If: has-value
   Then: return next
   Else: (next-value <- return (next []),
	  Into: (results Next*) Write: (True, next-value),
	  return next-value))
);;

"We don't put the 'atomic' in here to stay compositional as long as possible"
define-method (var Bump) (
  Into: var Write: (1 + (Read: var))
);;

let valid-orders = map [x: [x, x]] ['sale_date', 'cost', 'address'] in
let [_, order] = Find: [[l, r]: l == order] In: valid-orders
                 IfAbsent: [_, 'sale_date']
in ...
;;