Clojure 3 Recursion, Higher-order-functions 27-Aug-15.

Slides:



Advertisements
Similar presentations
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.
Advertisements

1 Scheme and Functional Programming Aaron Bloomfield CS 415 Fall 2005.
More about functions Plus a few random things. 2 Tail recursion A function is said to be tail recursive if the recursive call is the very last thing it.
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.
CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp
ML: a quasi-functional language with strong typing Conventional syntax: - val x = 5; (*user input *) val x = 5: int (*system response*) - fun len lis =
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)
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
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.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
F UNCTIONAL P ROGRAMMING 05 Functions. F UNCTIONS - G LOBAL F UNCTIONS fboundp Tells whether there is a function with a given symbol as its name > (fboundp.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
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.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
Λ => Scheme for Rubyists. Scheme History Authors: Guy Steele and Gerald Sussman Structure and Interpretation of Computer Programs (SICP) by Abelson &
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
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.
Clojure 2 Feb 7,
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
Functional Programming in Scheme and Lisp.
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.
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Python Functions.
PROGRAMMING LANGUAGES: PROLOG, CLOJURE, F# Jared Wheeler.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
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.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
1.SML Docs Standard Basis 2.First-Class Functions Anonymous Style Points Higher-Order 3.Examples Agenda.
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.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
Lets and Loops Tail Recursion.
Information and Computer Sciences University of Hawaii, Manoa
Clojure “Lisp Reloaded”.
Types CSCE 314 Spring 2016.
Section 15.4, 15.6 plus other materials
ML: a quasi-functional language with strong typing
Methods Chapter 6.
Functions and patterns
Modern JavaScript Develop And Design
Functions Declarations, Function Expressions and IIFEs
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.
Clojure 4 Sequences 5-Dec-18.
Thinking in Clojure 1-Jan-19.
Thinking in Clojure 1-Jan-19.
Homework Any Questions?.
Clojure “Lisp Reloaded”.
Clojure “Lisp Reloaded”.
(more) Python.
Recursion, Higher-order-functions
Announcements Quiz 5 HW6 due October 23
Important Concepts from Clojure
Clojure 2 22-Apr-19.
Functions and patterns
Clojure 3 1-Jun-19.
Thinking in Clojure 8-Jun-19.
Lisp.
Presentation transcript:

Clojure 3 Recursion, Higher-order-functions 27-Aug-15

Running Clojure C:\Users\Dave>cd C:\Programs\clojure C:\Programs\clojure-1.2.0>java -cp clojure.jar clojure.main Clojure user=> (load-file "E:/Programming/Clojure programs on E/test.clj") #'user/fruit user=> The response, #'user/fruit, is because “fruit” was the last thing defined on this file Although jEdit has a clojure mode, I don’t like it Syntax coloring is good, but indentation is strange (buggy?) and agressive The lisp mode doesn’t syntax color as well, but indents properly Comments: A “doc” string is a string that goes just before the parameter list Other comments start with a semicolon ( ; ) and extend to the end of the line

3 Functions The syntax to define a named function is: (defn function_name docstring? [ 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 A Clojure function can be overloaded (have different bodies for different parameter lists) Syntax: (defn function_name docstring? ([ arguments ] expressions )... ([ arguments ] expressions ) )

Tail recursion A recursive function is one that calls itself A recursive function typically has three parts: 1.One or more base cases that solve the simplest cases of the problem without recurring 2.Recursive calls to solve subproblems that are simpler but of the same type as the given problem 3.Code to augment solutions to subproblems into solutions of the given problem A function is tail recursive if the recursive call is the very last thing that the function does In other words, part 3 above is empty—no additional work need be done If the function has multiple exits, it is tail recursive only if every recursive call returns without doing additional work

Façades A façade is a function that provides a different (usually better) interface to another function Often this means supplying arguments that are only used for initialization In Clojure it’s easy to define a function within another function This allows an “uglier” version of the function to be hidden Functions can also be overloaded 5

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).

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)) ) ) )

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))) ) )

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).

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)) ) ) )

Functions that take functions Functional programming languages allow you to use a function as a parameter to another function Almost all functional programming languages provide these three extremely useful functions: map applies a function to every element of a sequence, giving a sequence of the results filter applies a predicate to every element of a sequence, giving a sequence of the results reduce (or fold) applies a binary operation “between” each pair of elements, giving a single (non-sequence) result There are often different versions for left- and right-associative operations, and for providing or not providing an initial value 11

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)

Anonymous functions An anonymous function has the syntax: (fn [ parameters ] body ) Example: (fn [x] (* x x)) Anonymous functions are used when The function body is short and simple, and It is only needed in one place

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))

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

reduce user=> (defn my-reduce [f init lst] (cond (empty? lst) init :else (recur f (f init (first lst)) (rest lst)) ) ) #'user/my-reduce user=> (my-reduce + 0 '( )) 66 user=> (my-reduce * 1 '(2 3 4)) 24

Functions that return functions A closure is a function that contains and works with, not only its parameters, but values from the scope in which it was defined Currying creates a new function with fewer arguments than the original function Function composition combines two or more functions into a new function 17

Closures I user=> (defn rangechecker [min max] (fn [num] (and (>= num min) (<= num max))) ) #'user/rangechecker user=> (def in-range? (rangechecker 0 100)) #'user/in-range? user=> (in-range? 75) true user=> (in-range? 101) false

Closures II user=> (defn adjust-range [min max] (fn [num] (cond ( num max) max :else num )) ) #'user/adjust-range user=> (def adjust (adjust-range 0 100)) #'user/adjust user=> (adjust 75) 75 user=> (adjust 101) 100

Partial functions (currying) (partial f arg1 arg2 arg3 & more ) Takes a function f and fewer than the normal arguments to f, and returns a fn that takes a variable number of additional args. When called, the returned function calls f with args + additional args. user=> (def hundred-times (partial * 100)) #'user/hundred-times user=> (hundred-times 5) 500

Function composition user=> (def negtimes (comp - *)) #'user/negtimes user=> (negtimes 5 3) -15 user=> (def third (comp first rest rest)) #'user/third user=> (third [ ]) 33 user=> (third '(:a :b :c :d)) :c

The End