// F# versions of some C# programs. // Compile program to .exe with fsc exptree.fs // To run in interactive console, type #load "c:\\..path..\\filename";; open System // food list type food = Fruit of int | Veg of int*string | Meat of int*int;; type flist = Nofood | Cons of food*flist;; let car = function | Cons(a,b) -> a; // this is an incomplete definition - automatically // throws exception. let cdr = function | Nofood -> Nofood | Cons(a,b) -> b; let myfood = Cons(Fruit(50),Cons(Veg(100,"green"),Cons(Meat(200,1),Nofood))); Console.WriteLine(car(myfood)); // function to add up all the calories let rec cals = function | Nofood -> 0 | Cons(Veg(x,y),t) -> x + cals(t) | Cons(Fruit(x),t) -> x + cals(t) | Cons(Meat(x,_),t) -> x + cals(t);; // function to test if food list is ordered fruit-veg-meat. // I wrote this using a variety of styles. type foodstate = Fstate | Vstate | Mstate;; let rec ordered = function | (state, Cons(Fruit(_),t)) -> not(state=Vstate || state=Mstate) && ordered(Fstate,t); | (Mstate, Cons(Veg(_,_),t)) -> false; | (_, Cons(Veg(_,_),t)) -> ordered(Vstate,t); | (_, Cons(Meat(_,_),t)) -> ordered(Mstate,t); | (_,Nofood) -> true;; // note two ; here Console.WriteLine("is ordered? " + string(ordered(Fstate,myfood)));;