I had to model it in Python

before writing it in OCaml.
This commit is contained in:
Simon Forman 2022-09-28 18:21:13 -07:00
parent 4200c6708e
commit cdec813b24
2 changed files with 120 additions and 0 deletions

View File

@ -0,0 +1,98 @@
| JoyInt i -> string_of_int i
| JoyList el -> "[" ^ ^ "]"
Secret happy robot^
let lex = Genlex.make_lexer ["["; "]"];;
let s = Stream.of_string "1[2]3";;
let t = lex s;;
val t : Genlex.token Stream.t = <abstr>
Stream.next t;;
Genlex.token = Genlex.Int 1
Genlex.token = Genlex.Kwd "["
let rec parse_one : token list -> joy_type * token list = fun tokens ->
match tokens with
| [] -> raise (ParseError "Empty list.")
| head :: tail ->
match head with
| Left_bracket -> parse_list tail []
| Right_bracket -> raise (ParseError "Extra closing bracket.")
| Token tok ->
match tok with
| "true" -> (joy_true, tail)
| "false"-> (joy_false, tail)
| _ -> (JoySymbol tok, tail)
and parse_list : token list -> joy_list -> joy_type * token list = fun tokens acc ->
(* collect terms until ']' *)
match tokens with
| [] -> raise (ParseError "Missing closing bracket.")
| _ -> let item, rest = parse_one tokens in
JoyList (item :: acc), parse_list rest acc
match head with
| Left_bracket -> parse_list tail []
| Right_bracket -> raise (ParseError "Extra closing bracket.")
| Token tok ->
let foo n = n + 1
(* parameterize foo and you have map *)
let rec poo tokens acc =
match tokens with
| [] -> acc
| head :: tail ->
let item = foo head in
item :: poo tail acc
(* Let's generalize foo to get and return tails *)
let bar n = n + 1
let baz tail = tail
let foo head tail =
bar head, baz tail
let rec poo tokens acc =
match tokens with
| [] -> acc
| head :: tail ->
let item, rest = foo head tail in
item :: poo rest acc
.
* for Vim, add this line to ~/.vimrc:
set rtp^="/usr/home/sforman/.opam/default/share/ocp-indent/vim"
<><> merlin.4.6-414 installed successfully ><><><><><><><><><><><><><><><><><><>
=> merlin installed.
Quick setup for VIM
-------------------
Append this to your .vimrc to add merlin to vim's runtime-path:
let g:opamshare = substitute(system('opam var share'),'\n$','','''')
execute "set rtp+=" . g:opamshare . "/merlin/vim"
Also run the following line in vim to index the documentation:
:execute "helptags " . g:opamshare . "/merlin/vim/doc"

View File

@ -0,0 +1,22 @@
def f(string, start=0, acc=[]):
if start >= len(string):
return acc
if '[' == string[start]:
return [1] + f(string, start+1, acc)
if ']' == string[start]:
return [0] + f(string, start+1, acc)
if ' ' == string[start]:
return f(string, start+1, acc)
symbol, n = bar(string, start, start)
return [symbol] + f(string, n, acc)
def bar(string, start, end):
if end >= len(string) or string[end] in '[] ':
return string[start:end], end
return bar(string, start, end+1)
print(f("1[2[] 3]4"))