Skip to content

Examples

Ayush Jain edited this page Feb 27, 2016 · 13 revisions

99 bottles of beer

def ninetyNineBottles (): unit = {
   def toStr(x:num) : string = {
      if (x == 0)
      then { "no More"; }
      else { String.toString(x); }
   }

   def ninetyNine (x:num) : unit = {
      if(x==0)
      then {
         println("No more bottles of beer on the wall, no more bottles of beer.");
         println("Go to the store and buy some more, 99 bottles of beer on the wall.");   
      } 
      else {
         println(toStr(x) ^ "bottle of beer on the wall, " ^ toStr(x) ^  " bottle of beer.");
         if(x==2)
         then {
            println("Take one down and pass it around, " ^ toStr(x - 1) ^ " bottle of beer on the wall.");
            nintetyNine(x-1);
         }
         else{
            println("Take one down and pass it around, " ^ toStr(x - 1) ^ " bottles of beer on the wall.");
            nintetyNine(x-1);
         }
      }
   }
   ninetyNine(99);
}

GCD, using euclid's algorithm

def gcd (a:num, b:num):bool = 
   if (a == b) then a 
   else
      if (a > b)
      then gcd(a - b, b)
      else gcd(b - a, a)
;

Merge Sort

def merge (a : list num, b : list num) =
   if (List.hd(a) < List.hd(b))
   then List.cons(List.hd(a), merge(List.tl(a), b)
   else List.cons(List.hd(b), merge(a, List.tl(b))
;

def split (a : list num, start : num, end : num) : list num = 
   if (start != 0)
   then split(List.tl(num), start-1, num)
   else if (end == -1)
   then a
   else List.cons(List.hd(a), split(List.tl(a), start, end-1))
;

def mergeSort (a : list num) : list num = {
   val size = List.size(a);
   if (size == 0 || size == 1) 
   then a
   else merge(split(a, 0, n/2), split(a, n/2+1, size-1))
}
Clone this wiki locally