Functional Programming in C++ C++ Support for Functional Paradigm

Total Page:16

File Type:pdf, Size:1020Kb

Functional Programming in C++ C++ Support for Functional Paradigm Introduction Functional Programming in C++ C++ Support for Functional Paradigm Bartosz Kwaśniewski . Bartosz Kwaśniewski Functional Programming in C++ 1 / 131 “I wonder what would happen, if there were a language so complicated, so difficult to learn, that nobody would ever be able to swamp the market with programmers” Introduction Hi did it for all of us ;) Bjarne Stroustrup . Bartosz Kwaśniewski Functional Programming in C++ 2 / 131 Introduction Hi did it for all of us ;) “I wonder what would happen, if there were a language so complicated, so difficult to learn, that nobody would ever be able to swamp the market with programmers” Bjarne Stroustrup . Bartosz Kwaśniewski Functional Programming in C++ 2 / 131 I Is it true, is it really true? I What does it mean? I C++ supports or has just recently started to support functional programming I Questions: Introduction Claims and Questions I Claims: . Bartosz Kwaśniewski Functional Programming in C++ 3 / 131 I Is it true, is it really true? I What does it mean? I Questions: Introduction Claims and Questions I Claims: I C++ supports or has just recently started to support functional programming . Bartosz Kwaśniewski Functional Programming in C++ 3 / 131 I Is it true, is it really true? I What does it mean? Introduction Claims and Questions I Claims: I C++ supports or has just recently started to support functional programming I Questions: . Bartosz Kwaśniewski Functional Programming in C++ 3 / 131 I What does it mean? Introduction Claims and Questions I Claims: I C++ supports or has just recently started to support functional programming I Questions: I Is it true, is it really true? . Bartosz Kwaśniewski Functional Programming in C++ 3 / 131 Introduction Claims and Questions I Claims: I C++ supports or has just recently started to support functional programming I Questions: I Is it true, is it really true? I What does it mean? . Bartosz Kwaśniewski Functional Programming in C++ 3 / 131 2. You could use many styles including object oriented and functional to make better software 3. There is no other option, no turning back: you must learn the functional paradigm Introduction Key Messages 1. Paradigm shift towards functional programming is necessary and has already started . Bartosz Kwaśniewski Functional Programming in C++ 4 / 131 3. There is no other option, no turning back: you must learn the functional paradigm Introduction Key Messages 1. Paradigm shift towards functional programming is necessary and has already started 2. You could use many styles including object oriented and functional to make better software . Bartosz Kwaśniewski Functional Programming in C++ 4 / 131 Introduction Key Messages 1. Paradigm shift towards functional programming is necessary and has already started 2. You could use many styles including object oriented and functional to make better software 3. There is no other option, no turning back: you must learn the functional paradigm . Bartosz Kwaśniewski Functional Programming in C++ 4 / 131 I Moore’s law (free lunch is over) I Heat wall, no more clock race (max 3.4GHz) I Multi-core arrival (solution) I Concurrent software (require redesign) I Object oriented pitfalls I Composability (concurrency not scale well) I Different approach: functional programming (purity, immutability) Introduction But, Why? I Why? . Bartosz Kwaśniewski Functional Programming in C++ 5 / 131 I Heat wall, no more clock race (max 3.4GHz) I Multi-core arrival (solution) I Concurrent software (require redesign) I Object oriented pitfalls I Composability (concurrency not scale well) I Different approach: functional programming (purity, immutability) Introduction But, Why? I Why? I Moore’s law (free lunch is over) . Bartosz Kwaśniewski Functional Programming in C++ 5 / 131 I Multi-core arrival (solution) I Concurrent software (require redesign) I Object oriented pitfalls I Composability (concurrency not scale well) I Different approach: functional programming (purity, immutability) Introduction But, Why? I Why? I Moore’s law (free lunch is over) I Heat wall, no more clock race (max 3.4GHz) . Bartosz Kwaśniewski Functional Programming in C++ 5 / 131 I Concurrent software (require redesign) I Object oriented pitfalls I Composability (concurrency not scale well) I Different approach: functional programming (purity, immutability) Introduction But, Why? I Why? I Moore’s law (free lunch is over) I Heat wall, no more clock race (max 3.4GHz) I Multi-core arrival (solution) . Bartosz Kwaśniewski Functional Programming in C++ 5 / 131 I Object oriented pitfalls I Composability (concurrency not scale well) I Different approach: functional programming (purity, immutability) Introduction But, Why? I Why? I Moore’s law (free lunch is over) I Heat wall, no more clock race (max 3.4GHz) I Multi-core arrival (solution) I Concurrent software (require redesign) . Bartosz Kwaśniewski Functional Programming in C++ 5 / 131 I Composability (concurrency not scale well) I Different approach: functional programming (purity, immutability) Introduction But, Why? I Why? I Moore’s law (free lunch is over) I Heat wall, no more clock race (max 3.4GHz) I Multi-core arrival (solution) I Concurrent software (require redesign) I Object oriented pitfalls . Bartosz Kwaśniewski Functional Programming in C++ 5 / 131 I Different approach: functional programming (purity, immutability) Introduction But, Why? I Why? I Moore’s law (free lunch is over) I Heat wall, no more clock race (max 3.4GHz) I Multi-core arrival (solution) I Concurrent software (require redesign) I Object oriented pitfalls I Composability (concurrency not scale well) . Bartosz Kwaśniewski Functional Programming in C++ 5 / 131 Introduction But, Why? I Why? I Moore’s law (free lunch is over) I Heat wall, no more clock race (max 3.4GHz) I Multi-core arrival (solution) I Concurrent software (require redesign) I Object oriented pitfalls I Composability (concurrency not scale well) I Different approach: functional programming (purity, immutability) . Bartosz Kwaśniewski Functional Programming in C++ 5 / 131 “It was only supposed to be a joke. Anyone with half a brain can see that object-oriented programming is counter-intuitive, illogical and inefficient” Bjarne Stroustrup “When the limestone of imperative programming is worn away, the granite of functional programming will be observed.” Simon Peyton Jones (GHC) Introduction Really smart guy’s says “The problem with object-oriented languages is that if you wanted a banana but what you got was a gorilla holding the banana and the entire jungle” Joe Armstrong, Erlang Creator . Bartosz Kwaśniewski Functional Programming in C++ 6 / 131 “When the limestone of imperative programming is worn away, the granite of functional programming will be observed.” Simon Peyton Jones (GHC) Introduction Really smart guy’s says “The problem with object-oriented languages is that if you wanted a banana but what you got was a gorilla holding the banana and the entire jungle” Joe Armstrong, Erlang Creator “It was only supposed to be a joke. Anyone with half a brain can see that object-oriented programming is counter-intuitive, illogical and inefficient” Bjarne Stroustrup . Bartosz Kwaśniewski Functional Programming in C++ 6 / 131 Introduction Really smart guy’s says “The problem with object-oriented languages is that if you wanted a banana but what you got was a gorilla holding the banana and the entire jungle” Joe Armstrong, Erlang Creator “It was only supposed to be a joke. Anyone with half a brain can see that object-oriented programming is counter-intuitive, illogical and inefficient” Bjarne Stroustrup “When the limestone of imperative programming is worn away, the granite of functional programming will be observed.” Simon Peyton Jones (GHC) . Bartosz Kwaśniewski Functional Programming in C++ 6 / 131 Introduction Table of Contents 1 Introduction 2 Programming Paradigms 3 Functional Programming 4 C++ Metaprogramming as Functional Language 5 Conclusion . Bartosz Kwaśniewski Functional Programming in C++ 7 / 131 I What does it mean that a language supports a paradigm well? Programming Paradigms About Programming Paradigms . Bartosz Kwaśniewski Functional Programming in C++ 8 / 131 Programming Paradigms About Programming Paradigms I What does it mean that a language supports a paradigm well? . Bartosz Kwaśniewski Functional Programming in C++ 8 / 131 Programming style or approach based on a co- herent set of programming concepts aimed to solve particular kind of problem. Programming Paradigms Paradigm Definition I What is a paradigm? . Bartosz Kwaśniewski Functional Programming in C++ 9 / 131 Programming Paradigms Paradigm Definition I What is a paradigm? Programming style or approach based on a co- herent set of programming concepts aimed to solve particular kind of problem. Bartosz Kwaśniewski Functional Programming in C++ 9 / 131 Programming Paradigms Programming Languages, Paradigms and Concepts . Bartosz Kwaśniewski Functional Programming in C++ 10 / 131 1. Real and different problems need different programming concepts to solve them cleanly 2. However: this requires the expetise level 1. Programming using more than one programming style, each to its best effect 2. The same as just ”programming” but using different features in combination as needed I Why do we need multiparagim languages? Programming Paradigms Multiparadigm Programming I What is Multiparadigm programming? . Bartosz Kwaśniewski Functional Programming in C++ 11 / 131 1. Real and different problems need different programming concepts to solve them cleanly 2. However:
Recommended publications
  • CSCI 2041: Lazy Evaluation
    CSCI 2041: Lazy Evaluation Chris Kauffman Last Updated: Wed Dec 5 12:32:32 CST 2018 1 Logistics Reading Lab13: Lazy/Streams I Module Lazy on lazy Covers basics of delayed evaluation computation I Module Stream on streams A5: Calculon Lambdas/Closures I Arithmetic language Briefly discuss these as they interpreter pertain Calculon I 2X credit for assignment I 5 Required Problems 100pts Goals I 5 Option Problems 50pts I Eager Evaluation I Milestone due Wed 12/5 I Lazy Evaluation I Final submit Tue 12/11 I Streams 2 Evaluation Strategies Eager Evaluation Lazy Evaluation I Most languages employ I An alternative is lazy eager evaluation evaluation I Execute instructions as I Execute instructions only as control reaches associated expression results are needed code (call by need) I Corresponds closely to I Higher-level idea with actual machine execution advantages and disadvantages I In pure computations, evaluation strategy doesn’t matter: will produce the same results I With side-effects, when code is run matter, particular for I/O which may see different printing orders 3 Exercise: Side-Effects and Evaluation Strategy Most common place to see differences between Eager/Lazy eval is when functions are called I Eager eval: eval argument expressions, call functions with results I Lazy eval: call function with un-evaluated expressions, eval as results are needed Consider the following expression let print_it expr = printf "Printing it\n"; printf "%d\n" expr; ;; print_it (begin printf "Evaluating\n"; 5; end);; Predict results and output for both Eager and Lazy Eval strategies 4 Answers: Side-Effects and Evaluation Strategy let print_it expr = printf "Printing it\n"; printf "%d\n" expr; ;; print_it (begin printf "Evaluating\n"; 5; end);; Evaluation > ocamlc eager_v_lazy.ml > ./a.out Eager Eval # ocaml’s default Evaluating Printing it 5 Lazy Eval Printing it Evaluating 5 5 OCaml and explicit lazy Computations I OCaml’s default model is eager evaluation BUT.
    [Show full text]
  • Lecture 4. Higher-Order Functions Functional Programming
    Lecture 4. Higher-order functions Functional Programming [Faculty of Science Information and Computing Sciences] 0 I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state [Faculty of Science Information and Computing Sciences] 1 I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto [Faculty of Science Information and Computing Sciences] 1 I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell [Faculty of Science Information and Computing Sciences] 1 Goal
    [Show full text]
  • Higher-Order Functions 15-150: Principles of Functional Programming – Lecture 13
    Higher-order Functions 15-150: Principles of Functional Programming { Lecture 13 Giselle Reis By now you might feel like you have a pretty good idea of what is going on in functional program- ming, but in reality we have used only a fragment of the language. In this lecture we see what more we can do and what gives the name functional to this paradigm. Let's take a step back and look at ML's typing system: we have basic types (such as int, string, etc.), tuples of types (t*t' ) and functions of a type to a type (t ->t' ). In a grammar style (where α is a basic type): τ ::= α j τ ∗ τ j τ ! τ What types allowed by this grammar have we not used so far? Well, we could, for instance, have a function below a tuple. Or even a function within a function, couldn't we? The following are completely valid types: int*(int -> int) int ->(int -> int) (int -> int) -> int The first one is a pair in which the first element is an integer and the second one is a function from integers to integers. The second one is a function from integers to functions (which have type int -> int). The third type is a function from functions to integers. The two last types are examples of higher-order functions1, i.e., a function which: • receives a function as a parameter; or • returns a function. Functions can be used like any other value. They are first-class citizens. Maybe this seems strange at first, but I am sure you have used higher-order functions before without noticing it.
    [Show full text]
  • Clojure, Given the Pun on Closure, Representing Anything Specific
    dynamic, functional programming for the JVM “It (the logo) was designed by my brother, Tom Hickey. “It I wanted to involve c (c#), l (lisp) and j (java). I don't think we ever really discussed the colors Once I came up with Clojure, given the pun on closure, representing anything specific. I always vaguely the available domains and vast emptiness of the thought of them as earth and sky.” - Rich Hickey googlespace, it was an easy decision..” - Rich Hickey Mark Volkmann [email protected] Functional Programming (FP) In the spirit of saying OO is is ... encapsulation, inheritance and polymorphism ... • Pure Functions • produce results that only depend on inputs, not any global state • do not have side effects such as Real applications need some changing global state, file I/O or database updates side effects, but they should be clearly identified and isolated. • First Class Functions • can be held in variables • can be passed to and returned from other functions • Higher Order Functions • functions that do one or both of these: • accept other functions as arguments and execute them zero or more times • return another function 2 ... FP is ... Closures • main use is to pass • special functions that retain access to variables a block of code that were in their scope when the closure was created to a function • Partial Application • ability to create new functions from existing ones that take fewer arguments • Currying • transforming a function of n arguments into a chain of n one argument functions • Continuations ability to save execution state and return to it later think browser • back button 3 ..
    [Show full text]
  • Pattern Matching
    Functional Programming Steven Lau March 2015 before function programming... https://www.youtube.com/watch?v=92WHN-pAFCs Models of computation ● Turing machine ○ invented by Alan Turing in 1936 ● Lambda calculus ○ invented by Alonzo Church in 1930 ● more... Turing machine ● A machine operates on an infinite tape (memory) and execute a program stored ● It may ○ read a symbol ○ write a symbol ○ move to the left cell ○ move to the right cell ○ change the machine’s state ○ halt Turing machine Have some fun http://www.google.com/logos/2012/turing-doodle-static.html http://www.ioi2012.org/wp-content/uploads/2011/12/Odometer.pdf http://wcipeg.com/problems/desc/ioi1211 Turing machine incrementer state symbol action next_state _____ state 0 __1__ state 1 0 _ or 0 write 1 1 _10__ state 2 __1__ state 1 0 1 write 0 2 _10__ state 0 __1__ state 0 _00__ state 2 1 _ left 0 __0__ state 2 _00__ state 0 __0__ state 0 1 0 or 1 right 1 100__ state 1 _10__ state 1 2 0 left 0 100__ state 1 _10__ state 1 100__ state 1 _10__ state 1 100__ state 1 _10__ state 0 100__ state 0 _11__ state 1 101__ state 1 _11__ state 1 101__ state 1 _11__ state 0 101__ state 0 λ-calculus Beware! ● think mathematical, not C++/Pascal ● (parentheses) are for grouping ● variables cannot be mutated ○ x = 1 OK ○ x = 2 NO ○ x = x + 1 NO λ-calculus Simplification 1 of 2: ● Only anonymous functions are used ○ f(x) = x2+1 f(1) = 12+1 = 2 is written as ○ (λx.x2+1)(1) = 12+1 = 2 note that f = λx.x2+1 λ-calculus Simplification 2 of 2: ● Only unary functions are used ○ a binary function can be written as a unary function that return another unary function ○ (λ(x,y).x+y)(1,2) = 1+2 = 3 is written as [(λx.(λy.x+y))(1)](2) = [(λy.1+y)](2) = 1+2 = 3 ○ this technique is known as Currying Haskell Curry λ-calculus ● A lambda term has 3 forms: ○ x ○ λx.A ○ AB where x is a variable, A and B are lambda terms.
    [Show full text]
  • Topic 6: Partial Application, Function Composition and Type Classes
    Recommended Exercises and Readings Topic 6: Partial Application, • From Haskell: The craft of functional programming (3rd Ed.) Function Composition and Type • Exercises: • 11.11, 11.12 Classes • 12.30, 12.31, 12.32, 12.33, 12.34, 12.35 • 13.1, 13.2, 13.3, 13.4, 13.7, 13.8, 13.9, 13.11 • If you have time: 12.37, 12.38, 12.39, 12.40, 12.41, 12.42 • Readings: • Chapter 11.3, and 11.4 • Chapter 12.5 • Chapter 13.1, 13.2, 13.3 and 13.4 1 2 Functional Forms Curried and Uncurried Forms • The parameters to a function can be viewed in two different ways • Uncurried form • As a single combined unit • Parameters are bundled into a tuple and passed as a group • All values are passed as one tuple • Can be used in Haskell • How we typically think about parameter passing in Java, C++, Python, Pascal, C#, … • Typically only when there is a specific need to do • As a sequence of values that are passed one at a time • As each value is passed, a new function is formed that requires one fewer parameters • Curried form than its predecessor • Parameters are passed to a function sequentially • How parameters are passed in Haskell • Standard form in Haskell • But it’s not a detail that we need to concentrate on except when we want to make use of it • Functions can be transformed from one form to the other 3 4 Curried and Uncurried Forms Curried and Uncurried Forms • A function in curried form • Why use curried form? • Permits partial application multiply :: Int ‐> Int ‐> Int • Standard way to define functions in Haskell multiply x y = x * y • A function of n+1
    [Show full text]
  • Lambda Calculus and Functional Programming
    Global Journal of Researches in Engineering Vol. 10 Issue 2 (Ver 1.0) June 2010 P a g e | 47 Lambda Calculus and Functional Programming Anahid Bassiri1Mohammad Reza. Malek2 GJRE Classification (FOR) 080299, 010199, 010203, Pouria Amirian3 010109 Abstract-The lambda calculus can be thought of as an idealized, Basis concept of a Turing machine is the present day Von minimalistic programming language. It is capable of expressing Neumann computers. Conceptually these are Turing any algorithm, and it is this fact that makes the model of machines with random access registers. Imperative functional programming an important one. This paper is programming languages such as FORTRAN, Pascal etcetera focused on introducing lambda calculus and its application. As as well as all the assembler languages are based on the way an application dikjestra algorithm is implemented using a Turing machine is instructed by a sequence of statements. lambda calculus. As program shows algorithm is more understandable using lambda calculus in comparison with In addition functional programming languages, like other imperative languages. Miranda, ML etcetera, are based on the lambda calculus. Functional programming is a programming paradigm that I. INTRODUCTION treats computation as the evaluation of mathematical ambda calculus (λ-calculus) is a useful device to make functions and avoids state and mutable data. It emphasizes L the theories realizable. Lambda calculus, introduced by the application of functions, in contrast with the imperative Alonzo Church and Stephen Cole Kleene in the 1930s is a programming style that emphasizes changes in state. formal system designed to investigate function definition, Lambda calculus provides a theoretical framework for function application and recursion in mathematical logic and describing functions and their evaluation.
    [Show full text]
  • Functional Programming Lecture 1: Introduction
    Functional Programming Lecture 13: FP in the Real World Viliam Lisý Artificial Intelligence Center Department of Computer Science FEE, Czech Technical University in Prague [email protected] 1 Mixed paradigm languages Functional programming is great easy parallelism and concurrency referential transparency, encapsulation compact declarative code Imperative programming is great more convenient I/O better performance in certain tasks There is no reason not to combine paradigms 2 3 Source: Wikipedia 4 Scala Quite popular with industry Multi-paradigm language • simple parallelism/concurrency • able to build enterprise solutions Runs on JVM 5 Scala vs. Haskell • Adam Szlachta's slides 6 Is Java 8 a Functional Language? Based on: https://jlordiales.me/2014/11/01/overview-java-8/ Functional language first class functions higher order functions pure functions (referential transparency) recursion closures currying and partial application 7 First class functions Previously, you could pass only classes in Java File[] directories = new File(".").listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); Java 8 has the concept of method reference File[] directories = new File(".").listFiles(File::isDirectory); 8 Lambdas Sometimes we want a single-purpose function File[] csvFiles = new File(".").listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getAbsolutePath().endsWith("csv"); } }); Java 8 has lambda functions for that File[] csvFiles = new File(".")
    [Show full text]
  • Notes on Functional Programming with Haskell
    Notes on Functional Programming with Haskell H. Conrad Cunningham [email protected] Multiparadigm Software Architecture Group Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA Fall Semester 2014 Copyright c 1994, 1995, 1997, 2003, 2007, 2010, 2014 by H. Conrad Cunningham Permission to copy and use this document for educational or research purposes of a non-commercial nature is hereby granted provided that this copyright notice is retained on all copies. All other rights are reserved by the author. H. Conrad Cunningham, D.Sc. Professor and Chair Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA [email protected] PREFACE TO 1995 EDITION I wrote this set of lecture notes for use in the course Functional Programming (CSCI 555) that I teach in the Department of Computer and Information Science at the Uni- versity of Mississippi. The course is open to advanced undergraduates and beginning graduate students. The first version of these notes were written as a part of my preparation for the fall semester 1993 offering of the course. This version reflects some restructuring and revision done for the fall 1994 offering of the course|or after completion of the class. For these classes, I used the following resources: Textbook { Richard Bird and Philip Wadler. Introduction to Functional Program- ming, Prentice Hall International, 1988 [2]. These notes more or less cover the material from chapters 1 through 6 plus selected material from chapters 7 through 9. Software { Gofer interpreter version 2.30 (2.28 in 1993) written by Mark P.
    [Show full text]
  • Purity in Erlang
    Purity in Erlang Mihalis Pitidis1 and Konstantinos Sagonas1,2 1 School of Electrical and Computer Engineering, National Technical University of Athens, Greece 2 Department of Information Technology, Uppsala University, Sweden [email protected], [email protected] Abstract. Motivated by a concrete goal, namely to extend Erlang with the abil- ity to employ user-defined guards, we developed a parameterized static analysis tool called PURITY, that classifies functions as referentially transparent (i.e., side- effect free with no dependency on the execution environment and never raising an exception), side-effect free with no dependencies but possibly raising excep- tions, or side-effect free but with possible dependencies and possibly raising ex- ceptions. We have applied PURITY on a large corpus of Erlang code bases and report experimental results showing the percentage of functions that the analysis definitely classifies in each category. Moreover, we discuss how our analysis has been incorporated on a development branch of the Erlang/OTP compiler in order to allow extending the language with user-defined guards. 1 Introduction Purity plays an important role in functional programming languages as it is a corner- stone of referential transparency, namely that the same language expression produces the same value when evaluated twice. Referential transparency helps in writing easy to test, robust and comprehensible code, makes equational reasoning possible, and aids program analysis and optimisation. In pure functional languages like Clean or Haskell, any side-effect or dependency on the state is captured by the type system and is reflected in the types of functions. In a language like ERLANG, which has been developed pri- marily with concurrency in mind, pure functions are not the norm and impure functions can freely be used interchangeably with pure ones.
    [Show full text]
  • Currying and Partial Application and Other Tasty Closure Recipes
    CS 251 Fall 20192019 Principles of of Programming Programming Languages Languages λ Ben Wood Currying and Partial Application and other tasty closure recipes https://cs.wellesley.edu/~cs251/f19/ Currying and Partial Application 1 More idioms for closures • Function composition • Currying and partial application • Callbacks (e.g., reactive programming, later) • Functions as data representation (later) Currying and Partial Application 2 Function composition fun compose (f,g) = fn x => f (g x) Closure “remembers” f and g : ('b -> 'c) * ('a -> 'b) -> ('a -> 'c) REPL prints something equivalent ML standard library provides infix operator o fun sqrt_of_abs i = Math.sqrt(Real.fromInt(abs i)) fun sqrt_of_abs i = (Math.sqrt o Real.fromInt o abs) i val sqrt_of_abs = Math.sqrt o Real.fromInt o abs Right to left. Currying and Partial Application 3 Pipelines (left-to-right composition) “Pipelines” of functions are common in functional programming. infix |> fun x |> f = f x fun sqrt_of_abs i = i |> abs |> Real.fromInt |> Math.sqrt (F#, Microsoft's ML flavor, defines this by default) Currying and Partial Application 4 Currying • Every ML function takes exactly one argument • Previously encoded n arguments via one n-tuple • Another way: Take one argument and return a function that takes another argument and… – Called “currying” after logician Haskell Curry Currying and Partial Application 6 Example val sorted3 = fn x => fn y => fn z => z >= y andalso y >= x val t1 = ((sorted3 7) 9) 11 • Calling (sorted3 7) returns a closure with: – Code fn y => fn z
    [Show full text]
  • Control Flow
    Control Flow COMS W4115 Prof. Stephen A. Edwards Spring 2002 Columbia University Department of Computer Science Control Flow “Time is Nature’s way of preventing everything from happening at once.” Scott identifies seven manifestations of this: 1. Sequencing foo(); bar(); 2. Selection if (a) foo(); 3. Iteration while (i<10) foo(i); 4. Procedures foo(10,20); 5. Recursion foo(int i) { foo(i-1); } 6. Concurrency foo() jj bar() 7. Nondeterminism do a -> foo(); [] b -> bar(); Ordering Within Expressions What code does a compiler generate for a = b + c + d; Most likely something like tmp = b + c; a = tmp + d; (Assumes left-to-right evaluation of expressions.) Order of Evaluation Why would you care? Expression evaluation can have side-effects. Floating-point numbers don’t behave like numbers. Side-effects int x = 0; int foo() { x += 5; return x; } int a = foo() + x + foo(); What’s the final value of a? Side-effects int x = 0; int foo() { x += 5; return x; } int a = foo() + x + foo(); GCC sets a=25. Sun’s C compiler gave a=20. C says expression evaluation order is implementation-dependent. Side-effects Java prescribes left-to-right evaluation. class Foo { static int x; static int foo() { x += 5; return x; } public static void main(String args[]) { int a = foo() + x + foo(); System.out.println(a); } } Always prints 20. Number Behavior Basic number axioms: a + x = a if and only if x = 0 Additive identity (a + b) + c = a + (b + c) Associative a(b + c) = ab + ac Distributive Misbehaving Floating-Point Numbers 1e20 + 1e-20 = 1e20 1e-20 1e20 (1 + 9e-7) + 9e-7 6= 1 + (9e-7 + 9e-7) 9e-7 1, so it is discarded, however, 1.8e-6 is large enough 1:00001(1:000001 − 1) 6= 1:00001 · 1:000001 − 1:00001 · 1 1:00001 · 1:000001 = 1:00001100001 requires too much intermediate precision.
    [Show full text]