Imperative Languages

Total Page:16

File Type:pdf, Size:1020Kb

Imperative Languages Lectures 4-5 Imperative languages Iztok Savnik, FAMNIT March, 2020. 1 Literature • John Mitchell, Concepts in Programming Languages, Cambridge Univ Press, 2003 (Chapters 5 and 8) • Michael L. Scott, Programming Language Pragmatics (3rd ed.), Elsevier, 2009 (Chapters 6 and 8) • Lecture by Jan Karabaš, Concepts of imperative programming, Programming II, FAMNIT, 2015 • Iztok Savnik, Koncepti programskih jezikov, Skripta (in Slovene), FAMNIT, 2013 (Chapter 4) Imperative languages • Functional programming – Program is a function – Outcome is done by the evaluation of the function – Does not matter how the result is produced • Imperative programming – Program is sequence of instructions (states of the machine) – Outcome is build in the execution of instructions – Instruction changes the contents of main memory Functional vs. imperative approach • Two abstract computation models – Functional – Imperative • Functional programming – λ-calculus, recursively-enumerable functions – Abstract machine (program) is represented by a λ- term, the outcome is obtained by its reduction • Imperative programming – The abstract machine is a Turing machine (finite state automaton), – The outcome is obtained when the final state is reached Example Let us compute the greatest common divisor of two integers C++ OCaml int gcd(int x, int y) { x = abs(x); y=abs(y); let rec gcd x y = while (y != 0) { if y = 0 then x int t = x % y; else gcd y (x mod y);; x = y; y = t; } Functional: values, recursion return x; Imperative: variables, loop, sequence } Imperative programming • Machine has read-write memory for storing variables • (Turing) machine consists of the states and instructions, which define computations and transitions between states • Execution means the changes of states of the machine rather than the evaluation (reduction) • The (way of) transitions are shaped (controlled) by the values of variables • Execution of instruction can change the values of variables - side-effects Structured control • Structured and unstructured control flow – Unstructured: goto statements – Structured: syntactical constructs direct computation • Structured programming, 1970 – »Revolution« in software engineering – Top-down design (i.e., progressive refinement) – Modularization of code – Structured types (records, sets, pointers multidimensional arrays) – Descriptive variable and constant names – Extensive commenting conventions Structured control • Most structured programming ideas were implemented in imperative languages – Pascal, C, Modula, Ada, Oberon, ... • Most of modern algorithms can be elegantly expressed in imperative languages Concepts of imperative languages • Read-write memory, variables • Instructions and sequences of instructions • Blocks • Conditional statements • Loops - conditional loops, iterations through ranges or through containers • Procedures and functions Program memory Variables • Memory of a program is organised into memory cells • Any cell can be accessed via its address; an integer, usually in range 0 – (262 − 1) • Variable is a symbolic name for a memory space of given size, which can be accessed by using the name instead of the address of the memory cell • Every program has symbol table, which stores the information about variables – Every record consists of: name (identifier), the address of the beginning of memory space, the size of allocated memory – Table changes during the execution of the program. Operations with variables • Program must allocate the memory space before the variable is used • The allocation can be either static or dynamic • Program reads the contents of the memory in the moment we refer to the identifier (name) • The contents of the memory referred by a variable is changed by assignment • The variable is freed either on the end of execution or on demand • Possible problems: – read/write to unallocated memory, concurrent write, memory leak. Models of variables • Value model of variables – Variable is a named container for a value – C, Pascal, Ada, ... • Reference model of variables – Named reference to a value – Algol 68, Clu, Lisp/Scheme, ML, Haskell, and Smalltalk – Reference model is not more expensive • Use multiple copies of immutable objects • The same performance as the value model Variables in C • Two important operators – Operator »&«: returns address of variable – Operator »*«: returns value of valiable at given address Value model int x = 1, y = 2, z = 3; x 1 int *ip; ip = &x; y 2 y = *ip; Symbol table RAM z 3 *ip = 0; *ip = *ip + 10; ip x 1 y = *ip + 1; y 2 z 3 *ip += 1; ip ++*ip; (*ip)++; Two important operators – Operator »&«: returns address of variable – Operator »*«: returns value of valiable at given address swap(&a, &b); ... a: void swap(int *px, int *py) { int temp; b: /* interchange *px and *py */ temp = *px; *px = *py; *py = temp; } Pointers and arrays in C • C has pointer arithmetic int a[10]; // a[0], a[1],..., a[9] pa = &a[0]; /* strlen: return length of string s */ int strlen(char *s) { int n; for (n = 0; *s != '\0', s++) n++; return n; } Variables in OCaml type ’a ref = {mutable contents:’a} • OCaml has weaker, but safer model of a variable – They are realised as the values of special reference type – Reference is initialised on creation by the referenced value – Memory space is automatically allocated using the type of referenced value – Function cannot be referenced – Assignment is a special function with resulting type unit – Reading has the type of the referenced variable – We do not have full access to the program’s memory – no pointers, no pointer arithmetics • Variables are similar to reference concept in C++ Example # let x = ref 2 ;; (* declaration and allocation val x : int ref = {contents=2} # !x;; (* reading, notice operator ‘!‘ - : int = 2 # x ;; (* reading of the reference - : int ref = {contents=2} # x := 5;; (* assignment - : unit = () # !x;; - : int = 5 # x := !x * !x;; (* reading, operation, and assignment - : unit = () # !x;; - : int = 25 Sequential control Sequential control is one of the basic principles of imperative programming languages 1. Sequences 2. Blocks 3. Condition statements 4. Loops Sequence • Sequence is foundamental abstraction used to describe algorithms – Instruction cycle of Von Neumann model LOOP: execute *PC; // execute instruction referenced by PC PC++; // increment programm counter (PC) by 1 goto LOOP; // loop • Sequence of instructions change the state of variables (memory) int t = x % y; x = y; y = t; let t = ref 0 let x = ref 42 Sequences in OCaml let y = ref 28 in t:= x mod y; x:=!y; y:=!x ;; • Syntax of OCaml sequences <expr1>; <expr2>; <expr3> (* list of expressions *) • Every expression in a OCaml sequence must be of type unit. # print_int 1; 2; 3;; Warning 10: this expression should have type unit. 1- : int = 3 # print_int 2; ignore 4; 6;; 2- : int = 6 Blocks • Imperative languages are typicaly block-structured languages • Block is a sequence of statements enclosed by some structural language form – Begin-end blocks, loop blocks, function body, etc. • Each block is represented using activation record – Includes parameters and local variables – Includes memory location for return value – Includes control pointers to be detailed in next lectures – Control pointers are used to control computation • Activation records are allocated on program stack Conditional statements • Machine languages use instructions for conditional jumps – Initial imperative approach • OCaml syntax if <cond_expr> then <expr_true> else <expr_false> ;; • Conditional statements is concept shared between imperative and functional languages – Both branches must agree on type in Ocaml – Conditional statement in Ocaml has value # (if 1 = 0 then 1 else 2) + 10;; - : int = 12 Loops – while-do • Repeat a block of commands while (or until) a condition is satisfied – Loop body changes the state of program • Statement while in OCaml while <cond_expr> do # let x = ref 42;; <sequence> val x : int ref = {contents = 42} done # let y = ref 28;; val y : int ref = {contents = 28} # let t = ref 0 in while !y != 0 do t := !x mod !y; x := !y; y := !t done;; - : unit = () # x;; - : int ref = {contents = 14} Loops – for statement • Statement for is classical construct of imperative prog. language # for i=1 to 10 do • Statement for in OCaml print_int i; print_string " " done; for <sym> = <exp1> to <exp2> do print_newline ();; <exp3> 1 2 3 4 5 6 7 8 9 10 done - : unit = () for <sym> = <exp1> downto <exp2> do # for i=10 downto 1 do <exp3> print_int i; done print_string " " done; print_newline () ;; 10 9 8 7 6 5 4 3 2 1 - : unit = () Loops – do-while statement • Loop condition is at the end of loop block do-while syntax /* itoa: convert n to characters in s */ void itoa(int n, char s[]) { do <sequence> int i, sign; while <cond_expr> if ((sign = n) < 0) /* record sign */ n = -n; /* make n positive */ • Statement i = 0; do { /* generate digits in reverse order */ repeat-until s[i++] = n % 10 + '0'; /* get next digit */ • Example: } while ((n /= 10) > 0); /* delete it */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s); } Loop control • Loop control in C programming language • Jumping out of loop – break • Jumping to loop condition – continue /* trim: remove trailing blanks, tabs, newlines */ for (i = 0; i < n; i++) int trim(char s[]) { if (a[i] < 0) int n; /* skip negative elements */ for (n = strlen(s)-1; n >= 0; n--) continue; if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n') ... break; /* do positive elements */ s[n+1] = '\0'; return n; } Procedures and functions • Abstraction is a process by
Recommended publications
  • Programming Paradigms & Object-Oriented
    4.3 (Programming Paradigms & Object-Oriented- Computer Science 9608 Programming) with Majid Tahir Syllabus Content: 4.3.1 Programming paradigms Show understanding of what is meant by a programming paradigm Show understanding of the characteristics of a number of programming paradigms (low- level, imperative (procedural), object-oriented, declarative) – low-level programming Demonstrate an ability to write low-level code that uses various address modes: o immediate, direct, indirect, indexed and relative (see Section 1.4.3 and Section 3.6.2) o imperative programming- see details in Section 2.3 (procedural programming) Object-oriented programming (OOP) o demonstrate an ability to solve a problem by designing appropriate classes o demonstrate an ability to write code that demonstrates the use of classes, inheritance, polymorphism and containment (aggregation) declarative programming o demonstrate an ability to solve a problem by writing appropriate facts and rules based on supplied information o demonstrate an ability to write code that can satisfy a goal using facts and rules Programming paradigms 1 4.3 (Programming Paradigms & Object-Oriented- Computer Science 9608 Programming) with Majid Tahir Programming paradigm: A programming paradigm is a set of programming concepts and is a fundamental style of programming. Each paradigm will support a different way of thinking and problem solving. Paradigms are supported by programming language features. Some programming languages support more than one paradigm. There are many different paradigms, not all mutually exclusive. Here are just a few different paradigms. Low-level programming paradigm The features of Low-level programming languages give us the ability to manipulate the contents of memory addresses and registers directly and exploit the architecture of a given processor.
    [Show full text]
  • 15-150 Lectures 27 and 28: Imperative Programming
    15-150 Lectures 27 and 28: Imperative Programming Lectures by Dan Licata April 24 and 26, 2012 In these lectures, we will show that imperative programming is a special case of functional programming. We will also investigate the relationship between imperative programming and par- allelism, and think about what happens when the two are combined. 1 Mutable Cells Functional programming is all about transforming data into new data. Imperative programming is all about updating and changing data. To get started with imperative programming, ML provides a type 'a ref representing mutable memory cells. This type is equipped with: • A constructor ref : 'a -> 'a ref. Evaluating ref v creates and returns a new memory cell containing the value v. Pattern-matching a cell with the pattern ref p gets the contents. • An operation := : 'a ref * 'a -> unit that updates the contents of a cell. For example: val account = ref 100 val (ref cur) = account val () = account := 400 val (ref cur) = account 1. In the first line, evaluating ref 100 creates a new memory cell containing the value 100, which we will write as a box: 100 and binds the variable account to this cell. 2. The next line pattern-matches account as ref cur, which binds cur to the value currently in the box, in this case 100. 3. The next line updates the box to contain the value 400. 4. The final line reads the current value in the box, in this case 400. 1 It's important to note that, with mutation, the same program can have different results if it is evaluated multiple times.
    [Show full text]
  • Functional and Imperative Object-Oriented Programming in Theory and Practice
    Uppsala universitet Inst. för informatik och media Functional and Imperative Object-Oriented Programming in Theory and Practice A Study of Online Discussions in the Programming Community Per Jernlund & Martin Stenberg Kurs: Examensarbete Nivå: C Termin: VT-19 Datum: 14-06-2019 Abstract Functional programming (FP) has progressively become more prevalent and techniques from the FP paradigm has been implemented in many different Imperative object-oriented programming (OOP) languages. However, there is no indication that OOP is going out of style. Nevertheless the increased popularity in FP has sparked new discussions across the Internet between the FP and OOP communities regarding a multitude of related aspects. These discussions could provide insights into the questions and challenges faced by programmers today. This thesis investigates these online discussions in a small and contemporary scale in order to identify the most discussed aspect of FP and OOP. Once identified the statements and claims made by various discussion participants were selected and compared to literature relating to the aspects and the theory behind the paradigms in order to determine whether there was any discrepancies between practitioners and theory. It was done in order to investigate whether the practitioners had different ideas in the form of best practices that could influence theories. The most discussed aspect within FP and OOP was immutability and state relating primarily to the aspects of concurrency and performance. ​ ​ ​ ​ ​ ​ This thesis presents a selection of representative quotes that illustrate the different points of view held by groups in the community and then addresses those claims by investigating what is said in literature.
    [Show full text]
  • Unit 2 — Imperative and Object-Oriented Paradigm
    Programming Paradigms Unit 2 — Imperative and Object-oriented Paradigm J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE PP 2018/19 Unit 2 – Imperative and Object-oriented Paradigm 1/38 Outline 1 Imperative Programming Paradigm 2 Abstract Data Types 3 Object-oriented Approach PP 2018/19 Unit 2 – Imperative and Object-oriented Paradigm 2/38 Imperative Programming Paradigm Outline 1 Imperative Programming Paradigm 2 Abstract Data Types 3 Object-oriented Approach PP 2018/19 Unit 2 – Imperative and Object-oriented Paradigm 3/38 Imperative Programming Paradigm Imperative Paradigm/1 The imperative paradigm is the oldest and most popular paradigm Based on the von Neumann architecture of computers Imperative programs define sequences of commands/statements for the computer that change a program state (i.e., set of variables) Commands are stored in memory and executed in the order found Commands retrieve data, perform a computation, and assign the result to a memory location Data ←→ Memory CPU (Data and Address Program) ←→ The hardware implementation of almost all Machine code computers is imperative 8B542408 83FA0077 06B80000 Machine code, which is native to the C9010000 008D0419 83FA0376 computer, and written in the imperative style B84AEBF1 5BC3 PP 2018/19 Unit 2 – Imperative and Object-oriented Paradigm 4/38 Imperative Programming Paradigm Imperative Paradigm/2 Central elements of imperative paradigm: Assigment statement: assigns values to memory locations and changes the current state of a program Variables refer
    [Show full text]
  • Comparative Studies of Programming Languages; Course Lecture Notes
    Comparative Studies of Programming Languages, COMP6411 Lecture Notes, Revision 1.9 Joey Paquet Serguei A. Mokhov (Eds.) August 5, 2010 arXiv:1007.2123v6 [cs.PL] 4 Aug 2010 2 Preface Lecture notes for the Comparative Studies of Programming Languages course, COMP6411, taught at the Department of Computer Science and Software Engineering, Faculty of Engineering and Computer Science, Concordia University, Montreal, QC, Canada. These notes include a compiled book of primarily related articles from the Wikipedia, the Free Encyclopedia [24], as well as Comparative Programming Languages book [7] and other resources, including our own. The original notes were compiled by Dr. Paquet [14] 3 4 Contents 1 Brief History and Genealogy of Programming Languages 7 1.1 Introduction . 7 1.1.1 Subreferences . 7 1.2 History . 7 1.2.1 Pre-computer era . 7 1.2.2 Subreferences . 8 1.2.3 Early computer era . 8 1.2.4 Subreferences . 8 1.2.5 Modern/Structured programming languages . 9 1.3 References . 19 2 Programming Paradigms 21 2.1 Introduction . 21 2.2 History . 21 2.2.1 Low-level: binary, assembly . 21 2.2.2 Procedural programming . 22 2.2.3 Object-oriented programming . 23 2.2.4 Declarative programming . 27 3 Program Evaluation 33 3.1 Program analysis and translation phases . 33 3.1.1 Front end . 33 3.1.2 Back end . 34 3.2 Compilation vs. interpretation . 34 3.2.1 Compilation . 34 3.2.2 Interpretation . 36 3.2.3 Subreferences . 37 3.3 Type System . 38 3.3.1 Type checking . 38 3.4 Memory management .
    [Show full text]
  • Functional Programming Functional Vs. Imperative Referential
    Functional vs. Imperative Referential transparency Imperative programming concerned with “how.” The main (good) property of functional programming is Functional Programming referential transparency. Functional programming concerned with “what.” COMS W4115 Every expression denotes a single value. Based on the mathematics of the lambda calculus Prof. Stephen A. Edwards (Church as opposed to Turing). The value cannot be changed by evaluating an expression Spring 2003 or by sharing it between different parts of the program. “Programming without variables” Columbia University No references to global data; there is no global data. Department of Computer Science It is inherently concise, elegant, and difficult to create subtle bugs in. There are no side-effects, unlike in referentially opaque Original version by Prof. Simon Parsons languages. It’s a cult: once you catch the functional bug, you never escape. The Joy of Pascal Strange behavior Variables program example(output) This prints 5 then 4. At the heart of the “problem” is fact that the global data var flag: boolean; flag affects the value of f. Odd since you expect function f(n:int): int In particular begin f (1) + f (2) = f (2) + f (1) if flag then f := n flag := not flag else f := 2*n; gives the offending behavior flag := not flag Mathematical functions only depend on their inputs end They have no memory Eliminating assignments eliminates such problems. begin In functional languages, variables not names for storage. flag := true; What does this print? Instead, they’re names that refer to particular values. writeln(f(1) + f(2)); writeln(f(2) + f(1)); Think of them as not very variables.
    [Show full text]
  • Imperative Programming Languages (IPL)
    Imperative Programming Languages (IPL) © Definitions: • The imperative (or procedural) paradigm is the closest to the structure of actual computers. • It is a model that is based on moving bits around and changing machine state • Programming languages based on the imperative paradigm have the following characteristics: The basic unit of abstraction is the PROCEDURE, whose basic structure is a sequence of statements that are executed in succession, abstracting the way that the program counter is incremented so as to proceed through a series of machine instructions residing in sequential hardware memory cells. The sequential flow of execution can be modified by conditional and looping statements (as well as by the very low-level goto statement found in many imperative languages), which abstract the conditional and unconditional branch instructions found in the underlying machine instruction set. Variables play a key role, and serve as abstractions of hardware memory cells. Typically, a given variable may assume many different values of the course of the execution of a program, just as a hardware memory cell may contain many different values. Thus, the assignment statement is a very important and frequently used statement. © Examples of imperative languages: • FORTRAN, Algol, COBOL, Pascal, C (and to some extent C++), BASIC, Ada - and many more. © PL/I • PL/I (1963-5): was one of the few languages that attempted to be a general purpose language, rather than aiming at a particular category of programming. • PL/I incorporated a blend of features from FORTRAN, ALGOL, and COBOL, plus allowed programmers to create concurrent tasks, handle run-time exceptions, use recursive procedures, and use pointers.
    [Show full text]
  • Comparative Studies of 10 Programming Languages Within 10 Diverse Criteria Revision 1.0
    Comparative Studies of 10 Programming Languages within 10 Diverse Criteria Revision 1.0 Rana Naim∗ Mohammad Fahim Nizam† Concordia University Montreal, Concordia University Montreal, Quebec, Canada Quebec, Canada [email protected] [email protected] Sheetal Hanamasagar‡ Jalal Noureddine§ Concordia University Montreal, Concordia University Montreal, Quebec, Canada Quebec, Canada [email protected] [email protected] Marinela Miladinova¶ Concordia University Montreal, Quebec, Canada [email protected] Abstract This is a survey on the programming languages: C++, JavaScript, AspectJ, C#, Haskell, Java, PHP, Scala, Scheme, and BPEL. Our survey work involves a comparative study of these ten programming languages with respect to the following criteria: secure programming practices, web application development, web service composition, OOP-based abstractions, reflection, aspect orientation, functional programming, declarative programming, batch scripting, and UI prototyping. We study these languages in the context of the above mentioned criteria and the level of support they provide for each one of them. Keywords: programming languages, programming paradigms, language features, language design and implementation 1 Introduction Choosing the best language that would satisfy all requirements for the given problem domain can be a difficult task. Some languages are better suited for specific applications than others. In order to select the proper one for the specific problem domain, one has to know what features it provides to support the requirements. Different languages support different paradigms, provide different abstractions, and have different levels of expressive power. Some are better suited to express algorithms and others are targeting the non-technical users. The question is then what is the best tool for a particular problem.
    [Show full text]
  • Concurrency and Parallelism in Functional Programming Languages
    Concurrency and Parallelism in Functional Programming Languages John Reppy [email protected] University of Chicago April 21 & 24, 2017 Introduction Outline I Programming models I Concurrent I Concurrent ML I Multithreading via continuations (if there is time) CML 2 Introduction Outline I Programming models I Concurrent I Concurrent ML I Multithreading via continuations (if there is time) CML 2 Introduction Outline I Programming models I Concurrent I Concurrent ML I Multithreading via continuations (if there is time) CML 2 Introduction Outline I Programming models I Concurrent I Concurrent ML I Multithreading via continuations (if there is time) CML 2 Introduction Outline I Programming models I Concurrent I Concurrent ML I Multithreading via continuations (if there is time) CML 2 Programming models Different language-design axes I Parallel vs. concurrent vs. distributed. I Implicitly parallel vs. implicitly threaded vs. explicitly threaded. I Deterministic vs. non-deterministic. I Shared state vs. shared-nothing. CML 3 Programming models Different language-design axes I Parallel vs. concurrent vs. distributed. I Implicitly parallel vs. implicitly threaded vs. explicitly threaded. I Deterministic vs. non-deterministic. I Shared state vs. shared-nothing. CML 3 Programming models Different language-design axes I Parallel vs. concurrent vs. distributed. I Implicitly parallel vs. implicitly threaded vs. explicitly threaded. I Deterministic vs. non-deterministic. I Shared state vs. shared-nothing. CML 3 Programming models Different language-design axes I Parallel vs. concurrent vs. distributed. I Implicitly parallel vs. implicitly threaded vs. explicitly threaded. I Deterministic vs. non-deterministic. I Shared state vs. shared-nothing. CML 3 Programming models Different language-design axes I Parallel vs.
    [Show full text]
  • Object-Oriented Programming
    Advanced practical Programming for Scientists Thorsten Koch Zuse Institute Berlin TU Berlin WS2014/15 Administrative stuff All emails related to this lecture should start with APPFS in the subject. Everybody participating in this lecture, please send an email to <[email protected]> with your Name and Matrikel-Nr. We will setup a mailing list for announcements and discussion. Everything is here http://www.zib.de/koch/lectures/ws2014_appfs.php If you need the certificate, regular attendance, completion of homework assignments, and in particular participation in our small programming project is expected. Grades will be based on the outcome and a few questions about it . No groups. Advanced Programming 3 Planned Topics Overview: Imperative, OOP, Functional, side effects, thread safe, Design by contract Design: Information hiding, Dependencies, Coding style, Input checking, Error Handling Tools: git, gdb, undodb, gnat Design: Overall program design, Data structures, Memory allocation Examples: BIP Enumerator, Shortest path/STP, SCIP call, Gas computation Languages and correctness: Design errors/problems C/C++, C89 / C99 / C11, Compiler switches, assert, flexelint, FP, How to write correct programs Testing: black-box, white-box, Unit tests, regression tests, error tests, speed tests Tools: gcov, jenkins, ctest, doxygen, make, gprof, valgrind, coverity Software metrics: Why, Examples, Is it useful? Other Languages: Ada 2012, Introduction, Comparison to C/C++, SPARK Parallel programming: OpenMP, MPI, Others (pthreads, OpenCL), Ada How to design large programs All information is subject to change. Advanced Programming 4 Attitudes Algorithm engineering refers to the process required to transform a pencil-and-paper algorithm into a robust, efficient, well tested, and easily usable implementation.
    [Show full text]
  • Clojure (For the Masses
    (Clojure (for the masses)) (author Tero Kadenius Tarmo Aidantausta) (date 30.03.2011) 1 Contents 1 Introduction 4 1.1 Dialect of Lisp . 4 1.2 Dynamic typing . 4 1.3 Functional programming . 4 2 Introduction to Clojure syntax 4 2.1 Lispy syntax . 5 2.1.1 Parentheses, parentheses, parentheses . 5 2.1.2 Lists . 6 2.1.3 Prex vs. inx notation . 6 2.1.4 Dening functions . 6 3 Functional vs. imperative programming 7 3.1 Imperative programming . 7 3.2 Object oriented programming . 7 3.3 Functional programming . 8 3.3.1 Functions as rst class objects . 8 3.3.2 Pure functions . 8 3.3.3 Higher-order functions . 9 3.4 Dierences . 10 3.5 Critique . 10 4 Closer look at Clojure 11 4.1 Syntax . 11 4.1.1 Reader . 11 4.1.2 Symbols . 11 4.1.3 Literals . 11 4.1.4 Lists . 11 4.1.5 Vectors . 12 4.1.6 Maps . 12 4.1.7 Sets . 12 4.2 Macros . 12 4.3 Evaluation . 13 4.4 Read-Eval-Print-Loop . 13 4.5 Data structures . 13 4.5.1 Sequences . 14 4.6 Control structures . 14 4.6.1 if . 14 4.6.2 do . 14 4.6.3 loop/recur . 14 2 5 Concurrency in Clojure 15 5.1 From serial to parallel computing . 15 5.2 Problems caused by imperative programming paradigm . 15 5.3 Simple things should be simple . 16 5.4 Reference types . 16 5.4.1 Vars . 16 5.4.2 Atoms . 17 5.4.3 Agents .
    [Show full text]
  • Imperative Programming in Sets with Atoms∗
    Imperative Programming in Sets with Atoms∗ Mikołaj Bojańczyk1 and Szymon Toruńczyk1 1 University of Warsaw, Warsaw, Poland Abstract We define an imperative programming language, which extends while programs with a type for storing atoms or hereditarily orbit-finite sets. To deal with an orbit-finite set, the language has a loop construction, which is executed in parallel for all elements of an orbit-finite set. We show examples of programs in this language, e.g. a program for minimising deterministic orbit-finite automata. Keywords and phrases Nominal sets, sets with atoms, while programs Introduction This paper introduces a programming language that works with sets with atoms, which appear in the literature under various other names: Fraenkel-Mostowski models [2], nominal sets [7], sets with urelements [1], permutation models [9]. Sets with atoms are an extended notion of a set – such sets are allowed to contain “atoms”. The existence of atoms is postulated as an axiom. The key role in the theory is played by permutations of atoms. For instance, if a, b, c, d are atoms, then the sets {a, {a, b, c}, {a, c}} {b, {b, c, d}, {b, d}} are equal up to permutation of atoms. In a more general setting, the atoms have some struc- ture, and instead of permutations one talks about automorphisms of the atoms. Suppose for instance that the atoms are real numbers, equipped with the successor relation x = y + 1 and linear order x < y. Then the sets {−1, 0, 0.3}{5.2, 6.2, 6.12} are equal up to automorphism of the atoms, but the sets {0, 2}{5.3, 8.3} are not.
    [Show full text]