Kurt Nørmark
Department of Computer Science, Aalborg University, Denmark
Abstract Previous lecture Next lecture Index References Contents | In this lecture we first introduce the main programming paradigms. Next we introduce the functional programming paradigm using the programming language Scheme. In this lecture We cover expressions, types, lists, definitions, and the basic function concept. A number of examples are given, when possible from the web domain. The introduction to the paradigm and Scheme is continued in the next lecture which covers name binding, recursion and iteration. |
Lisp and Scheme |
Lisp Slide Annotated slide Contents Index References Textbook | Lisp was invented by John McCarthy in the late fifties. |
|
|
|
|
Scheme Slide Annotated slide Contents Index References Textbook |
|
|
|
|
Exercise 2.2. Getting started with Scheme and LAML | The purpose of this exercises is learn the most important practical details of using a Scheme system on Unix. In case you insist to use Windows we will assume that you install the necessary software in your spare time. There is no time available to do that during the course exercises. Further details on installation of Scheme and LAML on Windows. You will have to choose between DrScheme and MzScheme. DrScheme is a user friendly environment for creating and running Scheme programs, with lots of menus and lots of help. However, it is somewhat awkward to use DrScheme with LAML. Only use DrScheme in this course if you cannot use Emacs, or if you are afraid of textually, command based tools. Follow this link for further details. MzScheme is the underlying engine of DrScheme. MzScheme is a simple read-eval-print loop, which let you enter an expression, evaluate and print the result. MzScheme is not very good for debugging and error tracing. MzScheme works well together with Emacs, and there is a nice connection between MzScheme and LAML. MzScheme used with Emacs is preferred on this course. Please go through the following steps:
|
Expressions and values |
Expressions, values, and types Slide Annotated slide Contents Index References Textbook | We will now describe and characterize the important concepts of expressions, values and types. |
|
Expressions are part of the source program, as written by the programmer. A function expression is called a lambda expression. We will encounter these important expressions later in this material. The primitive values are those which cannot be decomposed into more primitive parts. Some of the important primitive values are numbers, the two boolean values (true and false), and the characters of some character set. Primitive values stand as a contrast to composite values, such as lists and arrays, which are aggregations of parts, each of which are compositive or primitive values themselves. |
Examples of expressions and their values Slide Annotated slide Contents Index References Textbook |
The conditional expression is evaluated in two steps. First the boolean expression (even? x) is evaluated. If x is even, the boolean expression (even? x) evaluates to true and the trivial expression 7 is evaluated. Because x is 3 and therefore odd, the other expression (+ x 5) is evaluated, giving us the final value 8. It is important to realize that an if form does not evaluate all three constituent expressions at the outset. It first evaluates the boolean expression, and based on the outcome, it either evaluates the 'then part' or the 'else part'. Not both! We have much more to say about the order of evaluation of an if form in a later part of this material Regarding the lambda expression, the x in parentheses after lambda is the formal parameter of the function. the expression (+ x 1) is the body. In functions, the body is an expression - not a command. The HTML mirror expressions stem from the LAML libraries. The functions html, body, title, head, and p correspond to the HTML elements of the same names. In the LAML software, the HTML elements are mirrored as functions in Scheme. |
|
Evaluation of parenthesized expressions Slide Annotated slide Contents Index References Textbook | Here we will emphasize the rules of evaluating a form like (a b c d e) in Scheme |
The form (a b c d e) appears as a pair of parentheses with a number of entities inside. The question is how the parenthesized expression is evaluated, and which constraints apply to the evaluation. |
The evaluation of the empty pair of parentheses ( ) is often - in concrete Scheme systems - considered as the same as '( ), which returns the empty list. However, you should always quote the empty pair of parentheses to denote the empty list. |
|
Arithmetic expressions Slide Annotated slide Contents Index References Textbook | We will here point out that arithmetic expressions are written as fully parenthesized expressions with prefix notation |
|
The concept prefix notation: Using prefix notation the operator is given before the operands | Prefix notation stands as a contrast to infix and postfix notation. Infix notation is 'standard notation' in which the operand is found in between the operands. |
Table. Examples of arithmetic expressions. The prefix notation can be seen to the left, and the values of the expressions appear to the right. |
|
|
|
|
Equality in Scheme Slide Annotated slide Contents Index References Textbook | On this page we will discuss equality functions in Scheme |
|
|
Program: A sample interaction using and demonstrating the equivalence functions in Scheme. |
|
|
The read-eval-print loop Slide Annotated slide Contents Index References Textbook | On this page we will explain the idea and virtues of the so-called read-eval-print loop of Lisp and Scheme systems. |
Some authors talk about a REPL - Read Eval Print Loop. |
Program: A sample session with Scheme using a read eval print loop. |
|
Types |
Types Slide Annotated slide Contents Index References Textbook | Types plays an essential role in any programming language and any programming paradigm. In many languages types are used in the program text as constraints on variables and parameters. C, Pascal, and Java are such languages. In others, the types are inferred (somehow extracted from use of variables, parameters etc. relative to the ways the variables and parameters are used in operators and functions). ML is such a language. Yet in other languages, types are solely used to classify the values (data objects) at run time. Scheme is such a language. Thus, in Scheme we do not encounter types in the source program, but only at run time. |
|
|
|
Type checking Slide Annotated slide Contents Index References Textbook | As already mentioned the use of types in source programs makes it possible to deal with program correctness - at least in some simple sense. In this context, correctness is not relative to the overall intention or specification of the program. Rather, it is in relation to the legal use of values as input to operators and functions. |
|
According to section 1.1 the Scheme Report (R5RS) 'Scheme has latent as opposed to manifest types. Types are associated with values (also called objects) rather than with variables.' In our categorization, Scheme is strongly typed and types are dealt with at run time (on values) as a contrast to compile time (on variables). |
|
|
Static type checking Slide Annotated slide Contents Index References Textbook | We here make the distinction between explicit type decoration and implicit type inference, and explain the principled difference. |
|
Eksempel. Let us study the expression (+ x (string-length y)) |
|
An example of type checking Slide Annotated slide Contents Index References Textbook |
The example shows an arithmetic expression that will cause a type error with most type checkers. However, if x is even the sum can be evaluated to 6. If x is odd, we encounter a type error because we cannot add the integer 1 to the string "five". |
|
Types in functional programming languages Slide Annotated slide Contents Index References Textbook | Before we proceed we will compare the handling of types in Scheme with the handling of types in other functional programming languages. Specifically, we compare with Haskell and ML. |
|
|
|
Lists |
Proper lists Slide Annotated slide Contents Index References Textbook |
|
An illustration list construction and list selection. We first construct a list (d c b a) and we bind it to the variable lst. Next we select the first element, the tail of lst, the second element, and the second tail of lst. |
The constructor function cons takes an element e and a list f and constructs a new list. As illustrated above cons makes exactly one new cons cell, and no kind of list copying is involved at all. The selector car returns the first element of the list. A better name of car would be head . The selector cdr returns the list consisting of all but the first element in the list. A better name of cdr would be tail . |
In Scheme the empty list is denoted '(). When we in this context talk about the termination of the list we mean the value we get by following the cdr references to the end of the list structure. |
|
Symbolic expressions and improper lists Slide Annotated slide Contents Index References Textbook |
|
Figure. A symbolic expression which illustrates the most general form it can take - a binary tree |
Figure. The same symbolic expression laid out as a list. The expressions is a proper list if and only if h is the empty list. If h is not the empty list, the symbolic expression is an improper list. |
Exercise 2.3. Construction of symbolic expressions | Construct the symbolic expressions illustrated on this page via the cons primitive in Scheme.
The entities named a through h should be symbols. As a help, the rightmost part of the structure is made by (cons 'g 'h).
'g is equivalent to (quote g), meaning that g is not evaluated, but taken for face value. Experiment with h being the empty list. Try to use a proper list function, such as length, on your structures. |
Practical list construction Slide Annotated slide Contents Index References Textbook |
|
|
Table. Examples of list construction by use of cons , list and quoted list expressions. |
|
Exercise 2.4. Every second element of a list | Write a function, every-second-element, that returns every second element of a list. As examples (every-second-element '(a b c)) => (a c) (every-second-element '(a b c d)) => (a c) It is recommended that you formulate a recursive solution. Be sure to consider the basis case(s) carefully. It is often worthwhile to go for a more general solution than actually needed. Sometimes, in fact, the general solution is simpler than one of the more specialized solutions. Discuss possible generalizations of every-second-element, and implement the one you find most appropriate. |
|
List functions Slide Annotated slide Contents Index References Textbook |
We will here take a look at some of the most important list functions, as defined by the language itself. You are encouraged to read about them in the Scheme Report, to which we make a reference below. |
It should be noticed that the first element is designated as element number 0. Thus (list-ref '(a b c) 1) returns b |
|
Association lists Slide Annotated slide Contents Index References Textbook |
|
Table. Examples of association lists. The function assq uses eq? to compare the first parameter with the first element - the key element - in the pairs. As an alternative, we could use the function assoc, which uses equal? for comparison. A better and more general solution would be to pass the comparison function as parameter. Notice in this context, that both assq and assoc are 'traditional Lisp functions' and part of Scheme, as defined in the language report. |
|
Exercise 2.6. Creation of association lists | Program a function pair-up that constructs an association list from a list of keys and a list of values. As an example (pair-up '(a b c) (list 1 2 3)) should return ((a . 1) (b . 2) (c . 3)) Think of a reasonable solution in case the length of the key list is different from the length of the value list. |
Exercise 2.6. Association list and property lists | Association lists have been introduced at this page. An association list is a list of keyword-value pairs (a list of cons cells). Property lists are closely related to association lists. A property list is a 'flat list' of even length with alternating keys and values. The property list corresponding to the following association list ((a . 1) (b . 2) (c . 3)) is (a 1 b 2 c 3) Program a function that converts an association list to a property list. Next, program the function that converts a property list to an association list. |
|
Property lists Slide Annotated slide Contents Index References Textbook |
|
Table. A comparison between association lists and property lists. In this example we associate keys (represented as symbols) to string values. |
|
Program: A simple LAML document with emphasis on the attributes, represented as property lists.
There are four attribute lists (property lists, each with its own color). Notice
the CSS attribute css:text-decoration, given inline in the document . |
|
|
|
Tables as lists of rows Slide Annotated slide Contents Index References Textbook |
|
Table. Examples of table transposing, row elimination, and column elimination. We will program and illustrate these functions in a later exercise of this material. The function show-table is similar to table-0 from a LAML convenience library. Using higher-order functions it is rather easy to program the show-table function. We will come back to this later in these notes. |
|
|
|
Programs represented as lists Slide Annotated slide Contents Index References Textbook |
|
A sample Scheme program from the LAML library: |
Program: The function from the general library that converts different kinds of data to a number. |
|
|
|
Other Data Types |
Other simple types Slide Annotated slide Contents Index References Textbook |
|
|
|
Vectors Slide Annotated slide Contents Index References Textbook |
|
|
There is direct access to the elements of a vector. List elements are accessed by traversing a chain of references.
This reflects the basic differences between arrays and linked lists. The mode of construction for list is recursive, using the cons function. Lists are created incrementally:
New elements can be created when needed, and prepended to the list.
Vectors are allocated in one chunck, and cannot be enlarged or decreased incrementally. |
|
Strings Slide Annotated slide Contents Index References Textbook |
|
|
|
|
Definitions |
Definitions Slide Annotated slide Contents Index References Textbook |
The concept definition: A definition binds a name to a value |
Syntax: A name is first introduced and the name is bound to the value of the expression |
|
|
|
Functions |
The function concept Slide Annotated slide Contents Index References Textbook |
|
An extensionally defined function is defined by a set of pairs, enumerating corresponding elements in the domain and range. Notice that this causes practical problems if there are many different values in the domain of the function. An intensionally defined function is based on an algorithm that describes how to bring a value from the domain to the similar value in the range. This is a much more effective technique to definition of most the functions, we program in the functional paradigm. |
|
Lambda calculus Slide Annotated slide Contents Index References Textbook | We will here introduce the notation of the lambda calculus, mainly in order to understand the inspiration which led to the concept of lambda expressions in Lisp and Scheme. |
|
Table. A comparison of the notations of abstraction and combination (application) in the lambda calculus and Lisp. In some variants of lambda calculus there are more parentheses than shown here: (λ v . E). However, mathematicians tend to like ultra brief notation, and they often eliminate the parentheses. This stands as a contrast to Lisp and Scheme programmers. |
|
|
Functions in Scheme Slide Annotated slide Contents Index References Textbook |
|
Program: A sample read-eval-print session with lambda expressions and function objects. In a context where we define x to the number 6 we first evaluate a lambda expression.
Scheme acknowledges this by returning the function object, which prints like ' #<procedure> '. As
a contrast to numbers, lists, and other simple values, there is
no good surface representation of function values (function objects). Next we bind the name inc
to the same function object. More about name binding in a later part of this material. The expression (if (even? x) inc fac)
returns inc because the value of x is 6, and as such it is even. Therefore the value of ((if (even? x) inc fac) 5)
is the same as the value of (inc 5), namely 6. |
|
|
Function objects Slide Annotated slide Contents Index References Textbook |
The concept function object: A function object represents a function at run time. A function object is created as the value of a lambda expression | A function object is a first class value at run time, in the same way as numbers, lists and other data are values. This is different from more traditional programming languages, where procedural and functional abstractions have another status than ordinary data. | |
The concept closure: A function object is also known as a closure. | The name 'closure' is related to the interpretation of free names in the body expression of the function. Free names are used, but not defined in the body. In a function object (or closure) the free names are bound in the context of the lambda expression. This is a contrast to the case where the free names are bound in the context of the application of the function. |
|
Functions as first class values Slide Annotated slide Contents Index References Textbook |
|
The concept first class citizen: A first class citizen is an entity which can be passed as parameter to functions, returned as a result from a function, and organized as parts of data structures |
Program: A few interactions which illustrate the first class properties of function objects.
We bind the variable toplevel-html-elements to the list of the two functions html and frameset. Both
are HTML mirror functions defined in the LAML general library. We illustrate next that the value of the variable indeed is a list of two
functions. Thus, we have seen that we can organized functions as elements in lists.
The function cadr returns the second element of a list. It is equivalent to (compose car cdr), where compose is functional composition. In the third evaluation we apply the mirror function frameset on
a single frame. The last interaction shows the HTML rendering of the this. xml-render is a function defined in the LAML general library. |
|
|
Anonymous functions Slide Annotated slide Contents Index References Textbook |
|
Program: An illustration of anonymous functions. The function (lambda(x) (+ x 1)) is the function that adds one (to its parameter).
It is organized in a list side by side with the function that multiplies by five. Notice in this context that none of these
two functions are named. In the last interaction we apply the latter to the number 6. |
|
Lambda expressions in Scheme Slide Annotated slide Contents Index References Textbook |
Syntax: |
|
Syntax: |
|
|
Exercise 2.7. Parameter passing in Scheme | Familiarize yourself with the parameter passing rules of Scheme by trying out the following calls: ((lambda (x y z) (list x y z)) 1 2 3) ((lambda (x y z) (list x y z)) 1 2) ((lambda (x y z) (list x y z)) 1 2 3 4) ((lambda (x y z . r) (list x y z r)) 1 2 3) ((lambda (x y z . r) (list x y z r)) 1 2) ((lambda (x y z . r) (list x y z r)) 1 2 3 4) ((lambda r r) 1 2 3) ((lambda r r) 1 2) ((lambda r r) 1 2 3 4) Be sure that you can explain all the results |
Optional parameters of Scheme functions (1) Slide Annotated slide Contents Index References Textbook |
|
Program: A example of a function f that accepts optional-parameters. Besides the required parameter rp, the function accepts an arbitrary number of additional parameters,
the list of which are bound to the formal parameter optional-parameter-list. The function optional-parameter
from the LAML general library accesses information from optional-parameter-list. In case an optional parameter
is not passed, the default value (the last parameter of optional-parameter) applies.
|
|
Program: A number of calls of the function f. For clarity we define f as the first interaction. |
|
|
Optional parameters of Scheme functions (2) Slide Annotated slide Contents Index References Textbook |
|
We have demonstrated how we simulate optional parameter via the 'rest parameter list' mechanism in Scheme. It is also possible to simulate a keyword parameter mechanism. In a LAML context, this is done with respect to the passing of attributes to the HTML mirror functions. |
Closures Slide Annotated slide Contents Index References Textbook |
|
An illustration of a closure, as formed by the syntactical lambda expression together with the necessary free names |
|
Function definition in Scheme Slide Annotated slide Contents Index References Textbook |
|
Syntax: The ordinary way to bind f to the value of a lambda expressions |
|
Syntax: An equivalent syntactic sugaring with a more shallow parenthesis structure. Whenever Scheme identifies a list at the 'name place' in a define form, it carries out the transformation (define (f p1 p2) ...) => (define f (lambda (p1 p2) ...)) . Some Scheme programmers like the form (define (f p1 p2) ...) because the calling form (f p1 p2) is a constituent of the form (define (f p1 p2) ...) |
|
Simple web-related functions (1) Slide Annotated slide Contents Index References Textbook | We will here give a simple example of a web-related function. Much more interesting examples will appear later in the material. |
Program: The definition of a www-document function. The www-document function is useful if you want to abstract the HTML envelope formed by
the elements html, head, title, and body. If you need to pass attributes to html or body the proposed function is not adequate. |
|
Program: A sample application of the function www-document. Notice the way we pass a number of body contributions, which - as a list - are bound to the formal parameter body-forms. |
|
Program: The whole story - including the LAML context. |
|
Simple web-related functions (2) Slide Annotated slide Contents Index References Textbook | We will here show another simple function. |
Program: The definition of the indent-pixel function. This is a function which we use in many web documents to indent
the contents a number of pixels relative to its context.
Here we implement
the indentation by use of a table, in which the first column cell
is empty. As we will se, other possibilities exist. |
|
Program: An alternative version of theindent-pixel function. This version uses Cascading Style Sheets expressiveness. As it appears,
this is a more compact, and more direct way of achieving our indentation goal. |
Program: A sample application of indent-pixel with some initial LAML context (software loading). Notice the use of the XHTML mirror. |
|
Function exercises Slide Annotated slide Contents Index References Textbook |
Exercise 2.9. Colors in HTML |
In HTML we define colors as text strings of length 7:"#rstuvw" The symbols r, s, t, u, v, and w are all hexadecimal numbers between 0 and f (15). rs is in that way the hexadecimal representation for red, tu is the code for green, and vw is the code for blue. As an example, the text string "#ffffff" represents white and "#ff0000" is red. In Scheme we wish to represent a color as the list (color r g b) where color is a symbol, r is number between 0 and 255 which represents the amount of red, and g and b in a similar way the amount of green and blue in the color. Write a Scheme function that transforms a Scheme color to a HTML color string. It is a good training to program the function that converts decimal numbers to hexa decimal numbers. I suggest that you do that - I did it in fact in my solution! If you want to make life a little easier, the Scheme function (number->string n radix) is helpful (pass radix 16 as second parameter). |
Exercise 2.9. Letter case conversion | In many web documents it is desirable to control the letter case of selected words.
This allows us to present documents with consistent appearances.
Therefore it is helpful to be able to capitalize a string, to transform a string
to consist of upper case letters only, and to lower case letters only. Be sure
to leave non-alphabetic characters untouched. Also, be sure to handle
the Danish characters 'æ', 'ø', and 'å' (ASCII 230, 248, and 229 respectively). In addition, let us emphasize that
we want functions that do not mutate the input string by any means. (It means that
you are not allowed to modify the strings passed as input to your functions). Write functions capitalize-a-string, upcase-a-string, downcase-a-string for these purposes. As examples of their use, please study the following: (capitalize-a-string "monkey") => "Monkey" (upcase-a-string "monkey") => "MONKEY" (downcase-a-string "MONkey") => "monkey" Hint: I suggest that you program the necessary functions yourself. Convert the string to a list of ASCII codes, do the necessary transformations on this list, and convert the list of modified ASCII codes back to a string. The Scheme functions list->string and string->list are useful. Hint: If you want to make life a little easier (and learn less from this exercise...) you can use the Scheme functions char-upcase and char-downcase, which work on characters. But these functions do maybe not work on the Danish letters, so you you probably need some patches. |
Collected references Contents Index |
|
Chapter 2: Expressions, Types, and Functions
Course home Author home About producing this web Previous lecture (top) Next lecture (top) Previous lecture (bund) Next lecture (bund)
Generated: July 2, 2013, 09:14:42