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

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures           Code

Application Order

   
f1 lst = foldl (\acc x -> acc + x) 0 lst
  -   A fold takes a binary function (in this case (\acc x ->...), a starting value (in this case 0) for the accumulator (acc), and a list (in this case lst) to fold up. The binary function is repeatedly applied to the current accumulator value and a list element, in order, and produces a new current accumulator value. In this example foldl is used so the list elements are processed from left to right. The inferred type is f1::Num a => [a] -> a
 
f2 lst = foldl (\acc x -> [x] ++ acc) [] lst
  -   Another example of folding from the left.
Ex: (f2 [[1,2,3],[4,5,6]]) is [[4,5,6],[1,2,3]].
The inferred type is f2::[a] -> [a]
 
f3 lst = foldr (\acc x -> x ++ acc) [] lst
  -   The (nearly) same example using foldr instead of foldl.
Ex: (f3 [[1,2,3],[4,5,6]]) is [4,5,6,1,2,3].
The inferred type is f3::[[a]] -> [a]
 
v1a = sum (map sqrt [1..130])
v1b = sum $ map sqrt [1..130]


v2a = ((* ((div 8 ((+ 3) 4)))) 5)
v2b = (*) 5 $ div 8 $ (+) 3 4
  -   ($) right associates function calls. The statement
   v1a = sum map sqrt [1..130]
fails because sum attempts to be applied to the argument map, which is not a list. But parens can be used to perform the map first as is done in the first statement to the left. Operator ($) changes the order of application from right to left. Thus, v1b to the left has the same effect as v1a to the left. Statements v2a and v2b to the left are a second example of ($).
 
lsqrt l = map sqrt l
v3 = (sum . lsqrt) [1..130]
  -   (.) is syntactic sugar for function composition. The meaning of (.) is as follows:
   f . g = \x -> f(g(x))
   f . g . h = \x -> f(g(h(x)))
An example is shown on the left. The function lsqrt is defined to take the element-by-element sqrt of all numbers in a given list. Then (sum . lsqrt) means find the sum of the list that is output by lsqrt.