20-CS-4003-001 Organization of Programming Languages Fall 2017
Recursion

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures           Code

Example: merge sort

   
{- Merge two increasing lists -}
mrg::(Ord a) => [a] -> [a] -> [a]
mrg [] [] = []
mrg a [] = a
mrg [] a = a
mrg x y =
   if ((x !! 0) < (y !! 0)) then
      (x !! 0) : mrg (tail x) y
   else
      (y !! 0) : mrg x (tail y)

{- Split a list: keep even indexed items -}
splite::(Num a) => [a] -> [a]
splite [] = []
splite (a:[]) = [a]
splite (a:b:x) = a : splite x

{- Split a list: keep odd indexed items -}
splito::(Num a) => [a] -> [a]
splito [] = []
splito (a:[]) = []
splito (a:b:x) = b : splito x

{- Mergesort -}
srt::(Num a, Ord a) => [a] -> [a]
srt [] = []
srt (a:[]) = [a]
srt x = mrg (srt (splite x)) (srt (splito x))
 -  Sort a list of numbers in increasing order using the mergesort algorithm.