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

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures           Code

Example: maximum number in a list

findmax::(Num a, Ord a) => [a] -> a
findmax [] = -1
findmax [a] = a
findmax lst = max (lst !! 0) 
                  (findmax (drop 1 lst))
 -  Find the maximum number in a list. The top line shows the signature that is inferred by Haskell. The next three lines illustrate the pattern matching of the input that leads to execution of the appropriate statement. A -1 is returned for an empty list. The element of a single element list is returned. Otherwise, the greater of the leading element of lst and the maximum of the rest of lst is returned.
findmax::(Num a, Ord a) => [a] -> a
findmax [] = -1
findmax lst = last y  
    y = head lst : [ max a b
                   | a <- (drop 1 lst)
                   | b <- y ]
 -  Find the maximum in a list using a list comprehension. As tokens are added to y, the last one is always the maximum seen so far. After lst is scanned, just its last element is the value of findmax.