Scheme IV

and

Functional Programming in Other Languages

Input

  • A file is opened for reading with (open-input-file filename), which returns a handle to the file
  • To read a file use (read handle)
  • Reading is also done recusivley
In [ ]:
(define file (open-input-file "turing.txt"))
(define readFile
  (lambda (p)
    (let f ((x (read p)))
      (if (eof-object? x)
          '()
          (cons x (f (read p)))))))

(readFile file)
In [ ]:
(1966
 Alan
 Perlis
 Yale
 University
 Compilers
 1967
 Maurice
 Wilkes
 University
 of
 Cambridge
 Hardware
 1968
 Richard
 Hamming
 Bell
 Telephone
 Laboratories
 Coding
 Systems
 1969
 Marvin
 Minsky
 MIT
 AI
 .
 .
 . 
 2012
 Silvio
 Micali
 MIT
 Complexity
 Theory
 2013
 Leslie
 Lamport
 Microsoft
 Research
 Distributed
 Systems
 2014
 Michael
 Stonebraker
 MIT
 Databases)

Output

  • A file is opened for writing with (open-output-file filename), which returns a handle
    • If the file exists, it returns an error, rather than overwriting it
  • To write to a file use (write object handle)
  • Writing to a file isn't quite as messy
  • Formatted output (ie printf) isn't part of the language, many dialects implement some form of it
In [ ]:
(define file (open-output-file "schemeOut.txt"))
(write `("A" "small" "little" "text" "file") file)

("A" "small" "little" "text" "file")

In [ ]:
(define file (open-output-file "schemeOut2.txt"))
(map (lambda (x) (write x file)) `("A" "small" "little" "text" "file"))
In [ ]:
(#<void> #<void> #<void> #<void> #<void>)

"A""small""little""text""file"

In [ ]:
(define file (open-output-file "schemeOut3.txt"))
(map (lambda (x) (display x file)) `("A" "small" "little" "text" "file"))
In [ ]:
(#<void> #<void> #<void> #<void> #<void>)

Asmalllittletextfile

Sorting

  • Like the other languages we have looked at, Scheme usually provides a built in sort
    • It is not part of the official language, but is very commmon in the different dialects
    • Beacuse of this however, there is no standard syntax for it
  • The Scheme installed in GL uses the following syntax:
    (sort listToBeSorted sortFunction)
    

Sorting Example

To sort a list of numbers

(sort `(2 48 1 0 -1 100) <)

Which results in

(-1 0 1 2 48 100)

A more complex function can be used

(sort `((1 3 4) (2 49 0) (0 1 2)) (lambda (x y) (< (cadr x) (cadr y))))

Which gives

((0 1 2) (1 3 4) (2 49 0))

Functional Programming in Python

  • Python comes built in with the functions map and filter
  • There is no need for apply
    • All of these can be applied to any iterable (eg, list, tuple, dict, str, etc.)
  • Python also contains the keyword lambda

Lambda in Python

  • Lambda can be used to create an unnamed simple function in Python
  • Unlike lambda in Scheme, it can only contain one epxression
  • The syntax is:
    lambda var1,var2,....: expression
    

Lambda in Python Examples

In [2]:
square = lambda x: x*x
square(10)
Out[2]:
100
In [3]:
add = lambda a,b: a + b
add(1,2)
Out[3]:
3

Map in Python

  • The snytax of map is:
    map(function, iter1, iter2,.....,iterN)
    
  • Like Scheme, each iterable will provide a arugment for each call of function
  • Unlike Scheme, the iterables can be differing lengths
    • If this is the case, the shorter iterables will be padded with None

Map in Python Examples

In [10]:
map(int,["1",'2',"3","4"])
Out[10]:
[1, 2, 3, 4]
In [11]:
map(str.capitalize,["this","IS",'really',"USeful"])
Out[11]:
['This', 'Is', 'Really', 'Useful']
In [13]:
map(lambda x: x.capitalize(), ["this","WORKS",'TOo'])
Out[13]:
['This', 'Works', 'Too']
In [14]:
map(lambda x: x + " ", "What about this")
Out[14]:
['W ',
 'h ',
 'a ',
 't ',
 '  ',
 'a ',
 'b ',
 'o ',
 'u ',
 't ',
 '  ',
 't ',
 'h ',
 'i ',
 's ']
In [19]:
map(lambda x,y: x + " " + y , "What is this", "Another Stri") 
Out[19]:
['W A',
 'h n',
 'a o',
 't t',
 '  h',
 'i e',
 's r',
 '   ',
 't S',
 'h t',
 'i r',
 's i']
In [21]:
map(lambda x: x,{"dog":1,"cat":2,"frog":3})
Out[21]:
['dog', 'frog', 'cat']

Filter in Python

  • Takes in one iterable and returns that iterable with the items evaluating to false removed
  • Normally returns a list, but when passed a string or tuple, it will return a string or tuple
  • The syntax is:
    filter(function, iterable)
    

Filter in Python Examples

In [23]:
filter(lambda x: x > 0, [-5,2,-59,3])
Out[23]:
[2, 3]
In [24]:
filter(lambda x: x > 'm',"String")
Out[24]:
'trn'
In [27]:
filter(lambda x: type(x) == str, ["String",1000, ["string"], {"key":1}, 100.2,"String2"])
Out[27]:
['String', 'String2']

Find and Map in Python Practice

  • Write an expression that finds all the even squares of the numbers between 1 and 10
In [ ]:
 

Real World Example

Functional Programming in Lua

  • For all the influcence Scheme had on Lua, the functional paradigm was not one
  • You could write your own map function, but it wouldn't be that fast

Functional Programming in Java

  • Java 8 (Released 2014) introduced lambdas and a way to perform mapping and filtering
    • This was all planned to be in Java 7 (2011), but was defered
  • The mapping, filtering, etc. is done through the java.util.Streams class and it's derived classes
  • Java 8 also introduced the forEach method that is roughly equivalent to apply

Lambda in Java

  • The lambda function in Java can be a single line or many lines
  • It can also be explicity typed or not
    • If it is not explicitly typed, the then type is inferred from the context it is called in
  • The general syntax is
    (var1, var2, ....) -> { stmt1; stmt2; .... }
    
  • For the case with one parameter and one statement this can be simplified to
    var -> stmt
    

ForEach method

  • One of the simplest ways to start using lambdas in Java is with the forEach method.
  • All classes that implement Iterable have this method.
  • forEach has a return type of void
  • Example:
    ArrayList<String> strings =  
      new ArrayList<String>(
          Arrays.asList("Artificial Intelligence", "Theory", "Cybersecurity", "Machine Learning", "Computational Vision", "Data Visualization", "Computer Graphics", "Information Retrieval", "Wearable Computing", "Databases")); 
    strings.forEach(p -> System.out.println(p));
    

Streams API

  • For more advanced tasks, such as filtering or mapping, the streams API is used
  • To access the stream for a collection call the .stream() method.
    • Once the stream is retrieved, methods like filter and map can be chained together
    • To return from the stream, a call to collect is needed.
  • A call to stream actually returns a specific type of stream depending on the collection, but this detail isn't important for this class

Streams API Example

  • Given a list of numbers, find the square of each number in the list
List<Double> squares = numbers.stream().map(num -> num * num).collect(Collectors.toList());
  • Given a list of words and counts, find all words that end in _ADJ and add their counts together
Map<String,Integer> lambdaTotals = words.stream().filter(p -> p.getKey().endsWith("_ADJ")).collect(
         Collectors.groupingBy(x -> x.getKey().toLowerCase(),Collectors.summingInt(y -> y.getValue())));

Java Performance Comparison