Clojure 2 Feb 7, 2015 1.

Slides:



Advertisements
Similar presentations
Joshua Eckroth The Plan 1.Review some functions. 2.Write more functions. 3.Consider the nature of recursion. 4.Look at the.
Advertisements

Lisp. Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks.
Lists in Lisp and Scheme a. Lists are Lisp’s fundamental data structures, but there are others – Arrays, characters, strings, etc. – Common Lisp has moved.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
Clojure Template Tail Recursion. Hello, Factorial! The factorial function is everybody’s introduction to recursion (defn factorial-1 [n] (if (zero? n)
Imperative programming public int factorial (int N){ int F = 1; for(X=N; X>1; X-- ){ F= F*X; } return F; } Functional programming (defun factorial(N) (cond.
>(setf oldlist ) Constructing a list We know how to make a list in lisp; we simply write it: ‘4321( ) What if we want a new list with that list as a part?
Introductory Lisp Programming Lecture # 2 Main Topics –Basic Lisp data types –Lisp primitives –Details of list handling Cons cells (boxes) & their representation.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
Conditionals and Recursion "To iterate is human, to recurse divine." - L. Peter Deutsch.
Clojure 3 Recursion, Higher-order-functions 27-Aug-15.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
Clojure “Lisp on the JVM”. 2 Versions of LISP Lisp is an old language with many variants LISP is an acronym for List Processing language Invented by John.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
CSE-321 Programming Languages Introduction to Functional Programming (Part II) POSTECH March 13, 2006 박성우.
Λ => Scheme for Rubyists. Scheme History Authors: Guy Steele and Gerald Sussman Structure and Interpretation of Computer Programs (SICP) by Abelson &
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Solving N-Queens in Clojure
Clojure 4 Sequences 20-Oct-15. Clojure errors (NO_SOURCE_FILE:12) Useless--just means you’re running from the REPL shell java.lang.Exception: EOF while.
Chapter 9: Functional Programming in a Typed Language.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Feb 7, 2015 Thinking in Clojure. Jumping in We’ll quickly go through Clojure’s data types, some basic functions, and basic syntax Then we’ll get to the.
Basic LISP Programming Common LISP follows the algorithm below when interacting with users: loop read in an expression from the console; evaluate the expression;
Compiling Functional Programs Mooly Sagiv Chapter 7
CS 603: Programming Language Organization Lecture 10 Spring 2004 Department of Computer Science University of Alabama Joel Jones.
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
CS535 Programming Languages Chapter - 10 Functional Programming With Lists.
PROGRAMMING LANGUAGES: PROLOG, CLOJURE, F# Jared Wheeler.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
Clojure “Lisp Reloaded”. 2 Versions of LISP Lisp is an old language with many variants LISP is an acronym for List Processing language Lisp is alive and.
Basic Introduction to Lisp
From Lambda Calculus to LISP Functional Programming Academic Year Alessandro Cimatti
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Introduction to Functional Programming Part 1 – The Basic Concepts Winter Young
Fall 2016 Images from Sebesta: Copyright © 2012 Addison-Wesley. All rights reserved. The mind is everything. What you think you become. Buddha.
Fall 2016 Images from Sebesta: Copyright © 2012 Addison-Wesley. All rights reserved.
Lets and Loops Tail Recursion.
Clojure “Lisp Reloaded”.
Sequence, Selection, Iteration The IF Statement
Lists in Lisp and Scheme
Important Concepts from Clojure
Important Concepts from Clojure
Clojure “Lisp Reloaded”.
Thinking in Clojure 23-Nov-18.
Clojure to Haskell (It’s mostly syntax).
Clojure 4 Sequences 27-Nov-18.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Functions and Macros.
Clojure 4 Sequences 5-Dec-18.
Thinking in Clojure 1-Jan-19.
Thinking in Clojure 1-Jan-19.
Clojure “Lisp Reloaded”.
Clojure “Lisp Reloaded”.
Recursion, Higher-order-functions
Announcements Quiz 5 HW6 due October 23
Important Concepts from Clojure
Clojure 2 22-Apr-19.
Lecture # , , , , מבוא מורחב.
Clojure 3 1-Jun-19.
Thinking in Clojure 8-Jun-19.
Lisp.
More Scheme CS 331.
Defining Macros in Scheme
Presentation transcript:

Clojure 2 Feb 7, 2015 1

2

Functions The syntax to define a named function is: (defn function_name [arguments] expressions) The value of the function is the value of the last expression evaluated The syntax of a function call is (function arguments) Notice that the function being called is the first thing inside the parentheses This need not be the name of a function; it can be any expression that results in a function 3

Tail recursion (Erlang) Non-tail recursive function to find the length of a list: len([]) -> 0; len([_ | T]) -> 1 + len(T). Tail recursive function to find the length of a list: len(L) -> len(0, L). len(N, []) -> N; len(N, [_ | T]) -> len(N + 1, T). 4

Tail recursion (Clojure) Non-tail recursive function to find the length of a list: (defn len-1 [lst] (if (empty? lst) 0 (inc (len-1 (rest lst))) ) ) Tail recursive function to find the length of a list: (defn len-2 ([lst] (len-2 0 lst)) ([n lst] (if (empty? lst) n (len-2 (inc n) (rest lst))) ) ) 5

recur The previous function, len-2, is tail-recursive, but the compiler doesn’t optimize it into a loop Clojure runs on the JVM, which doesn’t optimize tail recursion Workaround: (defn len-2 ([lst] (len-2 0 lst)) ([n lst] (if (empty? lst) n (recur (inc n) (rest lst))) ) ) 6

Tail recursion (Erlang) Non-tail recursive function to find the factorial: factorial(1) -> 1; factorial(N) -> N * factorial(N - 1). Tail recursive function to find the factorial: factorial(N) -> factorial(1, N). factorial(Acc, 1) -> Acc; factorial(Acc, N) -> factorial(N * Acc, N - 1). 7

Tail recursion (Clojure) Non-tail recursive function to find the factorial: (defn factorial-1 [n] (if (= n 1) 1 (* n (factorial-1 (dec n))) ) Tail recursive function to find the factorial: (defn factorial-2 ([n] (factorial-2 1 n)) ([acc n] (if (= n 1) acc (recur (* n acc) (dec n)) ) ) ) 8

Loop version of factorial (def factorial (fn [n] (loop [cnt n acc 1] (if (zero? cnt) acc (recur (dec cnt) (* acc cnt))))))

Lists vs. vectors Lists uses (a b c) syntax, vectors use [a b c] Lists do standard Lisp evaluation (evaluate arguments, then apply function in first position to them). Vectors evaluate to themselves. Lists use the cons cell representation we have seen. Vectors use an internal representation that more efficiently supports extension.

Lists vs. vectors (continued) (def mylist '(a b c d)) user=> (cons 'q mylist) (q a b c d) ;; but mylist is unchanged (def myvec [a b c d]) user=> (conj myvec 'q) [a b c d q] ;; but myvec is unchanged

Vectors as stacks (def mystack [1 2 3]) user=> (peek mystack) 3 user=> (pop mystack) [1 2] ;; but mystack is unchanged user=> (conj mystack 4) [1 2 3 4] ;; but mystack is still unchanged

map (def fruit '((apple red) (banana yellow) (cherry red))) user=> (map first fruit) (apple banana cherry) (defn my-map [f lst] (if (empty? lst) () (cons (f (first lst)) (my-map f (rest lst))) ) ) user=> (map my-first fruit) (apple banana cherry) 13

Map using tail recursion (defn strict-map1 [f coll] (loop [coll coll, acc nil] (if (empty? Coll) (reverse acc) (recur (next coll) (cons (f (first coll)) acc)))))

Map using vectors (defn strict-map2 [f coll] (loop [coll coll, acc []] (if (empty? Coll) acc (recur (next coll) (conj acc (f (first coll))))))

Conj vs. cons The “right” way to add an element to any sequence in Clojure is conj. It always adds elements in the most efficient way. (cons 1 '(2 3)) => (1 2 3) (conj '(2 3) 1) => (1 2 3) (conj [2 3] 1) => [2 3 1]

Anonymous functions An anonymous function has the syntax: (fn [parameters] body) Example: (fn [x] (* x x)) 17

filter (def fruit '((apple red) (banana yellow) (cherry red))) user=> (filter (fn [x] (= (second x) 'red)) fruit) ((apple red) (cherry red)) (defn my-filter [p lst] (cond (empty? lst) () (p (first lst)) (cons (first lst) (my-filter p (rest lst))) :else (my-filter p (rest lst)) ) ) user=> (my-filter (fn [x] (= (second x) 'red)) fruit) ((apple red) (cherry red)) 18

Speaking of maps… A map or hash is a sequence of key/value pairs, enclosed in braces, for example, {:ace 1, :deuce 2, "trey" 3} Elements are separated by whitespace or commas It is helpful to use commas between key/value pairs A map is also a function: user=> (def cards {:ace 1, :deuce 2, "trey" 3}) #'user/cards user=> (cards :deuce) 2 Keywords are also functions: user=> (:deuce cards) 2 19

Immutability and Laziness Two key ideas in Clojure. Immutable objects never change once they are created. Why would Clojure do this? Invariants can be handled just at construction time. Reasoning about possible states is simplified. Equality has persistent meaning. Sharing is cheap. Just send a reference. Fosters concurrent programming.

Structural Sharing (def baselist (list :barnabas :adam)) (def lst1 (cons :willie baselist)) (def lst2 (cons :phoenix baselist)) (= (next lst1) (next lst2)) ; true (identical? (next lst1) (next lst2)) ;; also true

Simple tree example Demonstrates more complex structural sharing. xconj from pgs. 120-123 in Joy

The End