Advanced Functional Programming, 1DL Lecture 2, Cons T Åhs

Similar documents
All you need is fun. Cons T Åhs Keeper of The Code

Introduction to Erlang. Franck Petit / Sebastien Tixeuil

DISTRIBUTED SYSTEMS [COMP9243] Lecture 1.5: Erlang INTRODUCTION TO ERLANG BASICS: SEQUENTIAL PROGRAMMING 2. Slide 1

COSC441. Lecture 8 Introduction to Erlang

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

JavaScript: Coercion, Functions, Arrays

CS558 Programming Languages

SCHEME AND CALCULATOR 5b

Erlang 101. Google Doc

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

The Environment Model. Nate Foster Spring 2018

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

Programming Distributed Systems

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Functional Programming

CMSC 330: Organization of Programming Languages. Operational Semantics

CS390 Principles of Concurrency and Parallelism. Lecture Notes for Lecture #5 2/2/2012. Author: Jared Hall

An Introduction to Erlang. Richard Carlsson

Chapter 1. Fundamentals of Higher Order Programming

To figure this out we need a more precise understanding of how ML works

Message-passing concurrency in Erlang

The Environment Model

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Programming Languages

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name?

LFE - a lisp on the Erlang VM

CS 11 Haskell track: lecture 1

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Robust Erlang (PFP Lecture 11) John Hughes

An introduction introduction to functional functional programming programming using usin Haskell

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

A Third Look At ML. Chapter Nine Modern Programming Languages, 2nd ed. 1

Programming Languages

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

An Introduction to Erlang

Erlang: An Overview. Part 2 Concurrency and Distribution. Thanks to Richard Carlsson for most of the slides in this part

Functional programming in LISP

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

Principles of Programming Languages

functional programming in Python, part 2

Programming Languages

CSCI-GA Scripting Languages

CS 314 Principles of Programming Languages

FP Foundations, Scheme

Functional Programming

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Erlang. Functional Concurrent Distributed Soft real-time OTP (fault-tolerance, hot code update ) Open. Check the source code of generic behaviours

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Lecture 5: Declarative Programming. The Declarative Kernel Language Machine. September 12th, 2011

Erlang functional programming in a concurrent world

Erlang functional programming in a concurrent world Johan Montelius and Vladimir Vlassov

re-exam Concurrent Programming tda383/dit390 Date: Time: 14:00 18:00 Place: Maskinhuset (M)

Scheme: Expressions & Procedures

Programming Paradigms

Erlang. The Good the Bad and the Ugly. Joe Armstrong

Parallel Programming in Erlang (PFP Lecture 10) John Hughes

Defining Functions. CSc 372. Comparative Programming Languages. 5 : Haskell Function Definitions. Department of Computer Science University of Arizona

Evaluating Scheme Expressions

Reasoning About Programs Panagiotis Manolios

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

Introduction to Erlang

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Programming Languages and Compilers (CS 421)

OCaml. ML Flow. Complex types: Lists. Complex types: Lists. The PL for the discerning hacker. All elements must have same type.

CS 314 Principles of Programming Languages

L3 Programming September 19, OCaml Cheatsheet

Erlang. Functional Concurrent Distributed Soft real-time OTP (fault-tolerance, hot code update ) Open. Check the source code of generic behaviours

April 2 to April 4, 2018

Common LISP Tutorial 1 (Basic)

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Lecture 7: Primitive Recursion is Turing Computable. Michael Beeson

Erlang in the battlefield. Łukasz Kubica Telco BSS R&D Department Cracow Erlang Factory Lite, 2013

The Substitution Model

Implementing languages on the Erlang VM

FUNCTIONAL PROGRAMMING (1) PROF. SIMON PARSONS

Pharo Syntax in a Nutshell

Functional Programming. Pure Functional Programming

Programs as data first-order functional language type checking

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

Functional Programming Lecture 1: Introduction

An Introduction to Scheme

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

CS Lecture 7: The dynamic environment. Prof. Clarkson Spring Today s music: Down to Earth by Peter Gabriel from the WALL-E soundtrack

TAIL RECURSION, SCOPE, AND PROJECT 4 11

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Datatype declarations

Lecture 19: Functions, Types and Data Structures in Haskell

The Typed Racket Reference

Functional Programming

Let s Get Functional. Learn You Some Erlang for Great Good! 2013, Fred Hébert

Erlang: An Overview. Part 1 Sequential Erlang. Thanks to Richard Carlsson for the original version of many slides in this part

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

Functional Programming Languages (FPL)

Transcription:

Advanced Functional Programming, 1DL450 2012 Lecture 2, 2012-11-01 Cons T Åhs

Higher order functions hof() -> F = fun(x) -> X * X + 1 end, L = lists:map(f, [1, 2, 3], G = fun([]) -> nil; ([_ _]) -> cons end, Y = G(L), Y == nil. Syntax for anonymous functions is rather verbose Anonymous functions can have several clauses and use pattern matching A variable can be bound to a function Apply the function by using the variable instead of a function name Erlang got this right! What is the value of hof()?

Scoping revisited The scope of a variable binding is the rest of the function clause An expression can only access variables bound before the expression It is not possible to write a local recursive function in the ordinary way no(n) -> G = fun(0) -> 1; (N) -> N*G(N-1) end, G(N). It is possible to write a local recursive function using higher order functions Observe that G inside is just a function variable so it has to be passed to the function This is a good exercise! Write factorial in this way.

Higher order functions make_adder(n) -> fun(x) -> X + N end. inclist(l) -> lists:map(make_adder(3), L). whatlist(l) -> lists:map(fun make_adder/1, L). what(l, V) -> lists:map(fun(f) -> F(V) end, L). A function can be returned Notation for passing a named function as an argument Describe the functions inclist/1, whatlist/1 and what/2

Higher order functions cumbersome(m) -> MakeAdder = fun(n) -> fun(x) -> X + N end end, (MakeAdder(3))(M). Making curried functions suitable for partial application is possible, but quickly becomes a bit difficult to read. This is much easier in languages designed for this from the start.

Digression on closures make_adder(n) -> fun(x) -> X + N end. make_what(m) -> fun() -> fibonacci(m) end. do_it(d) -> D(). We have the cool feature of being able to return a closure, i.e., a function and the environment it was defined in. What does make_what/1 do? Returns a function of no (?) argument. It delays a computation! The body is evaluated only when we apply the result (of make_what/1) to (). We can thus save and represent a computation and do it later.

Variables can hold anything -module(sequences). -export([plus/2, minus/2]). plus(x, Y) -> X ++ Y. minus(x, Y) -> X -- Y. -module(numbers). -export([plus/2, minus/2]). plus(x, Y) -> X + Y. minus(x, Y) -> X - Y. -module(eval). -export([eval/4]). eval(m, F, A1, A2) -> M:F(A1, A2). 10> eval:eval(sequences, plus, [1,2,3], [a,b,c]). [1,2,3,a,b,c] 11> eval:eval(numbers, plus, 4, 7). 11 12>

Variables can hold anything A variable can be bound to ordinary values and functions (no surprise) function names modules This means you can send a whole module M as an argument to another function and the receiving function then calls known functions in M. Is this useful? Yes! It also means that given a module you can vary the actual function that is called by passing the name in a variable. Is this useful? Possibly. Both variations lead to the possibility to map, e.g., user input directly to Erlang modules and functions at runtime. Great way to make a really insecure system!

Variables can hold anything We had two modules which exported the same function names and arities They thus have the same interface! This concept exists in Erlang, but has the name behaviour It can be used in the same way as in, e.g., Java by providing several different implementations of the same (abstract) interface A very commonly used behaviour is the gen_server (for generic server) You provide the details and a generic server takes care of the generic parts.

BIFs (Built In Functions) BIFs exist to provide functionality that can t be done in pure Erlang interface with the real world for things like date, time and low level file system access conversion between primitive types such as atom_to_list (convert an atom to a string ) list_to_atom (convert a string to a (new) atom) etc There might also be BIFs for functions that can be implemented in Erlang, but a BIF will do it faster. Read documentation!

Standard Libraries Erlang comes with a large set of standard libraries, e.g, list function dictionaries of varying representation ets, dets - term storage, either in memory or on disk mnesia - database built on top of dets etc Read the documentation

List comprehensions Erlang has the standard higher order list functions such map, filter and foldl/r Erlang also has list comprehension for concise construction of lists Very similar to describing sets Examples foo(l) -> Squares = [X*X X <-L], Squares = lists:map(fun(x) -> X*X end, L), Appls = [{X, f(x)} X <- L, X > 2], Appls = lists:map(fun(x) -> {X, f(x)} end, lists:filter(fun(x) -> X > 2 end, L)), Appls = lists:foldr(fun(x, S) -> case X > 2 of true -> [{X, f(x)} S]; false -> S end end, [], L), {Squares, Appls}.

List comprehensions The left hand is an expression for constructing an element (evaluated The right hand side consists of generators (Var <- Expression) conditions or filters (a boolean expression on a Var) There can be several generators and conditions map(f, L) -> [F(X) X <- L]. filter(p, L) -> [X X <- L, P(X)]. combine(l) -> [{X, Y} X <- L, Y <- L, X=/=Y].

List comprehension Generate all permutations of a list The result of one generator can be used in another Very compact, but it takes some time to understand Exercise: write the same function without comprehension perms([]) -> [[]]; perms(l) -> [[X T] X <- L, T <- perms(l -- [X])].

Concurrent Programming Process model used in Erlang No shared memory between processes Problems when you have a shared and mutable state - Erlang has neither A process that dies does not corrupt the state of another process Communication by message passing; messages are copied (even within the same VM) Fast and easy process creation Initial size of a process is 3-400 bytes Easy distribution among cores (within same VM) VMs (on same hardware node) hardware nodes Communication is identical regardless of where the other process lives Processes are identified by PIDs (process identifiers)

What about state? Real world computations need state State is encoded in a process that reacts to messages init state wait for message compute new state and loop start() -> server(init_state()). server(state) -> server(process_message(get_msg(), State)). start the server and send messages to it

Managing Processes Three basic primitives are used to handle processes Create process - returns pid (process id) Send a message - returns Msg spawn(function) or spawn(m, F, Args) Pid! Msg Receive a message from the message queue (the process will wait if there is no message) - returns value of chosen expression receive Pattern 1 -> Expr 1 ; Pattern 2 -> Expr 2 ;... end

Selective receive Note that a receive will wait until it finds a message matching the pattern Messages might not be processed in the order they come This can be expensive since the message queue has to be searched receive foo -> f(..) end, receive bar -> g(..) end

Example start() -> server(0). server(count) -> NewCount = receive {report, Pid} -> Pid! Count, Count; _Msg -> Count + 1 end, server(newcount). 32> P = spawn(fun simple:start/0). <0.110.0> 33> P!foo. foo 34> P!foo. foo 35> P!foo. foo 36> P!{report, self()}. {report,<0.88.0>} 37> receive M -> M end. 3

Distribution made easy Distribute work load among a number of workers Input the work to be done, a queue of tasks the workers that performs the work (pids) What is specific for each problem? How to get a chunk of work from the queue How to combine results from a single worker with the result from the others

Distribution made easy We re done when the queue is empty and we have no active workers. We wait for a worker to return a result when the queue is empty or we have no passive workers We activate a worker when the queue is non empty and we have passive workers. Initial state is a queue of work, no active workers and a collection of passive workers.

Distribution made easy sequential(l) -> lists:filter(fun is_prime/1, L). process_work([], [], _, State) -> State; process_work(work, Active, Passive, State) when Work =:= []; Passive =:= [] -> receive {Worker, M} -> process_work(work, lists:delete(worker, Active), [Worker Passive], add_result(state, M)) end; process_work(work, Active, [Worker Passive], State) -> {Chunk, Rest} = get_chunk(state, Work), Worker! {self(), Chunk}, process_work(rest, [Worker Active], Passive, State). worker() -> receive {Pid, Work} -> Pid! {self(), sequential(work)}, worker() end.

Simple Message Passing Note that you have to set up the actual protocol yourself If you want a reply, a sent message should include a return address This goes for the reply as well - the original sender might want to know who sent the reply This might also apply to request identifiers so a more general request would contain both a return address and an identifier

More on process handling Linking processes for error handling and supervision Timeouts