Skip to content

Instantly share code, notes, and snippets.

@SteveGilham
SteveGilham / gist:fff084a70c993001d276
Created April 26, 2015 14:22
Continuation based character I/O
let putc (c: char) (k: continuation) =
let write () = System.Console.Write(c);
execute k
K write
let getc (g: char -> continuation) =
let read () = execute (g <| System.Console.ReadKey(true).KeyChar)
K read;;
let (<|) f x = (f x);;
let rec echo k =
let echoChar c = if c = '\r'
then putc '\n' k
else putc c (echo k)
getc echoChar;;
// Define a result type of a lexeme list or error message:
type lexerResult<'lexeme> =
Success of 'lexeme list
| Failure of string;;
// Define a type with a character source, a 'lexeme sink and an error string sink:
type lexerSystem<'lexeme> = {
input: unit -> char option;
output: 'lexeme -> unit;
error: string -> unit;
result: unit -> lexerResult<'lexeme> };;
// Read the output result and continue with (g result)
let lexComplete s g =
let complete () =
g (s.result ())
K complete;;
// Set the output to the failure state and continue with k
let lexFail s e k =
let storeError () =
s.error e
execute k
K storeError;;
@SteveGilham
SteveGilham / gist:a4669781cb22bacb10f0
Created April 26, 2015 14:18
Continuation based lexeme producer
// s is our lexerSystem
let lexGetChar s g =
K (fun () -> execute (g (s.input())));;
@SteveGilham
SteveGilham / gist:6941f00187d12e0eba43
Created April 26, 2015 14:17
Continuation based lexeme consumer
let lexPutLexeme s lexeme (k: continuation) =
let storeLexeme () =
s.output lexeme;
execute k
K storeLexeme;;
@SteveGilham
SteveGilham / gist:254b04aa9c8afec51ae1
Created April 26, 2015 14:16
Parse A or B (continuation based)
// (^^) associates on the right, which means that we can chain instances without requiring nested brackets
let ( ^^ ) (test, g1) (g2: 'x -> continuation) x =
(if test x then g1 else g2) x;;