Sunday 19 April 2009

LOGO Large Step Interpreter

open System;


let sin = Math.Sin
let cos = Math.Cos
let atan = Math.Atan


let float_of_int x = (float x)
let int_of_float x = (int x)


type logo = | Home
| Forward of int
| Turn of int
| For of int * logo list


let pi = 4.0 * atan 1.0
let dsin t = sin(pi * (float_of_int t) / 180.0)
and dcos t = cos(pi * (float_of_int t) / 180.0)


let rec interpret f (x,y,d) e =
let interpret' (x,y,d) e = match e with
| Home -> (0,0,0)
| Forward(n) -> (x + (int_of_float ((float n) * dsin d)), y + (int_of_float ((float n) * dcos d)), d)
| Turn(n) -> (x, y, d + n)
| For(i, xs) -> if i > 0 then
interpret f (interpret_prog f (x,y,d) xs) (For(i - 1, xs))
else
(x,y,d)
f (x,y,d)
interpret' (x,y,d) e
and interpret_prog f pos xs = match xs with
| x::xs' -> interpret_prog f (interpret f pos x) xs'
| [] -> pos


let current = (0, 0, 0)
let sample = [Home; For(20, [Turn 18; For(36, [Forward 10; Turn 10])])]


let result = interpret_prog (printf "%A") current sample

1 comment:

Swa said...

Wonderful. Thanks for sharing this, wished there would be more stuff around interpreters and F# on the net.