List Operations CSCE 314 Spring 2016. CSCE 314 – Programming Studio Tuple and List Patterns Pattern matching with wildcards for tuples fst (a, _) = a.

Slides:



Advertisements
Similar presentations
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Advertisements

Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Haskell Lets review some of the Haskell concepts you have been learning on your own. The answers are included, but try it yourself first.
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists Dan Grossman Winter 2013.
CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
Exercises – don’t use built in functions for these as we want the practice Write a recursive function to add up all the numbers in a list "flatten" a list.
0 LECTURE 5 LIST COMPREHENSIONS Graham Hutton University of Nottingham.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
0 PROGRAMMING IN HASKELL Chapter 6 - Recursive Functions.
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Cse536 Functional Programming 1 7/14/2015 Lecture #2, Sept 29, 2004 Reading Assignments –Begin Chapter 2 of the Text Home work #1 can be found on the webpage,
Comp 205: Comparative Programming Languages Functional Programming Languages: More Lists Recursive definitions List comprehensions Lecture notes, exercises,
Haskell Chapter 3, Part I. Pattern Matching  Pattern matching with tuples  Pattern matching with list comprehensions  As-patterns.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
Functional Programming Lecture 4 - More Lists Muffy Calder.
Haskell Chapter 1, Part II. List Comprehension  List comprehensions are a way to filter, transform and combine lists  Similar to mathematical set comprehensions.
Tuples and Lists Lecture 3, Programmeringsteknik del A.
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.
0 REVIEW OF HASKELL A lightening tour in 45 minutes.
0 PROGRAMMING IN HASKELL Chapter 7 - Defining Functions, List Comprehensions.
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.
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
Overview of the Haskell 98 Programming Language
A Third Look At ML Chapter NineModern Programming Languages, 2nd ed.1.
What is a Type? A type is a name for a collection of related values. For example, in Haskell the basic type Bool contains the two logical values: True.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
Recursion on Lists Lecture 5, Programmeringsteknik del A.
Kyung-Goo Doh Hanyang University - ERICAComputer Science & Engineering Functional Programming / Imperative Programming CSE215 Fundamentals of Program Design.
0 PROGRAMMING IN HASKELL Chapter 4 - Defining Functions.
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: More on Functions and List Comprehensions Dr. Hyunyoung Lee.
Chapter SevenModern Programming Languages1 A Second Look At ML.
CSED101 INTRODUCTION TO COMPUTING SUM TYPE 유환조 Hwanjo Yu.
0 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Odds and Ends,
Recursion Higher Order Functions CSCE 314 Spring 2016.
Haskell Chapter 4. Recursion  Like other languages  Base case  Recursive call  Author programs a number of built-in functions as examples.
Functional Programming Lecture 3 - Lists Muffy Calder.
Lecture 16: Advanced Topic: Functional Programming CS5363 Compiler and Programming Languages.
0 PROGRAMMING IN HASKELL Typeclasses and higher order functions Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and.
© M. Winter COSC 4P41 – Functional Programming Some functions id :: a -> a id x = x const :: a -> b -> a const k _ = k ($) :: (a -> b) -> a -> b.
Lecture 14: Advanced Topic: Functional Programming
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x2 | x  {1...5}} The set {1,4,9,16,25}
Functional Programming
Conditional Expressions
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
A lightening tour in 45 minutes
Haskell Chapter 4.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Computer Science 312 Haskell Lists 1.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists
PROGRAMMING IN HASKELL
CSCE 314: Programming Languages Dr. Dylan Shell
Haskell Types, Classes, and Functions, Currying, and Polymorphism
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Lazy Programming Lazy evaluation:
CSE 3302 Programming Languages
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Presentation transcript:

List Operations CSCE 314 Spring 2016

CSCE 314 – Programming Studio Tuple and List Patterns Pattern matching with wildcards for tuples fst (a, _) = a scd (_, b) = b Pattern matching with wildcards for lists pullsecond [_, a, _] = a This implies a list of 3 elements The _ indicates a single element of the list, when it is in the list. The _ can also indicate an entire list [ [a, b, c], _, _, [2, 4] ]

Spring 2016 CSCE 314 – Programming Studio Building a list: the cons operator ‘:’ : cons adds one element to the front of a list > 1 : [2, 3, 4] [1, 2, 3, 4] cons associates to the right: [1, 2, 3] = 1 : (2 : (3 : [])) = 1: 2: 3: [] Generally, should use parentheses to be clear! cons makes it easier to match list patterns (x:xs) – x is the first element in the list, xs is the remainder of the list

Spring 2016 CSCE 314 – Programming Studio Examples Patterns can be arbitrarily deep/complex. What are these patterns: f (a:b:c:d:e:fs) = a:b:c:d:e:[] list of at least 5 elements forms list of those first 5 g (_: (_, x): _) = x list of tuples, each with two elements takes second element of the second tuple h [[_]] = True singleton list, each element is a singleton list Identifies valid such lists, e.g. [[True]], or [[‘a’]], or [[1]]

Spring 2016 CSCE 314 – Programming Studio List Comprehensions (list generators) Can generate lists from other lists [x+x | x <-[1..10] ] [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] Can use multiple generators Applied left to right (like nested loops) [(x,y) | x <- [1..3], y <- [11..13]] [(1,11),(1,12),(1,13),(2,11),(2,12),(2,13),(3,11),(3,12), (3,13)] Notice that all the (1,_) elements come before the (2,_) ones Generators can use earlier generators (dependent generators) [(x,y) | x<-[1..3], y<-[x..3]] [(1,1),(1,2),(1,3),(2,2),(2,3),(3,3)]

Spring 2016 CSCE 314 – Programming Studio Dependent generator example What does this function do? somefunc xss = [x | xs <- xss, x <- xs] First, the type: somefunc :: [[a]] -> [a] Notice, we form xs from the elements of xss Then, we form x from the elements of xs And those x’s form the final list These are the elements of the elements of the list Basically, we concatenate the list somefunc [[1,2,3],[4],[5,6]] [1,2,3,4,5,6]

Spring 2016 CSCE 314 – Programming Studio Guards When using generators, we can apply guards, similar to the guards seen before Given as expressions, separated by commas Guards limit which combinations of generators are used (only the ones that give true guards [x | x <- [1..10], x<5] [1,2,3,4] [x | x <- [1..10], even x] [2,4,6,8,10]

Spring 2016 CSCE 314 – Programming Studio List Comprehension example Say we want a function that will list all primes up to n: primes :: Int -> [Int] First, we will create a function to compute all factors of a number: A number x is a factor of a number y if y mod x == 0 factors :: Int -> [Int] factors n = [x | x <- [1..n], n `mod` x == 0] Test: > factors 24 [1,2,3,4,6,8,12,24]

Spring 2016 CSCE 314 – Programming Studio List comprehension example (continued) Given factors, we want a function isprime A number x is prime if its only factors are 1 and x isprime :: Int -> Bool isprime n = factors n == [1,n] Test: > isprime 24 False > isprime 7 True

Spring 2016 CSCE 314 – Programming Studio List comprehension example (continued Given isprime, we can now write the primes function: primes :: Int -> [Int] primes n = [x | x <- [2..n], isprime x] Test > primes 20 [2,3,5,7,11,13,17,19]

Spring 2016 CSCE 314 – Programming Studio The zip function A useful list operation. Often as a tool in parts of bigger computation – to pair up items Take two lists and form a list of tuples Tuple is a pair, with one element from first list and corresponding from second Length of list is the length of the shortest input list > zip [1,2,3,4,5,6,7],[“red”,”green”,”blue”,”cyan”,”magenta”,”yellow”] [(1,”red”),(2,”green”),(3,”blue”),(4,”cyan”),(5,”magenta”),(6,”yellow”)]

Spring 2016 CSCE 314 – Programming Studio A zip example: testing for a sorted list Want a check to see if a list is sorted sorted :: Ord a => [a] -> Bool We first form pairs of adjacent elements in the list: pairs :: [a] -> [(a,a)] pairs xs = zip xs (tail xs) Test: > pairs [1, 5, 8, 9] [(1,5),(5,8),(8,9)]

Spring 2016 CSCE 314 – Programming Studio A zip example: testing for a sorted list (cont.) Given pairs, the list is sorted only if all pairs are in order Note: the and command, applied to a list, gives the “and” of all elements sorted :: Ord a => [a] -> Bool sorted xs = and [x<=y | (x,y) <- pairs xs] Test > sorted [1,5,8,9] True > sorted [1,8,5,9] False

Spring 2016 CSCE 314 – Programming Studio Recursion on lists Recursion works just like it did with integers Base case: typically the empty list [] Use the cons operator (:) to break/construct lists e.g. length [] = 0 length (_:xs) = 1 + length xs

Spring 2016 CSCE 314 – Programming Studio Example: quicksort Quicksort takes first element from a list, divides the remainder of the list into stuff before and stuff after, and then recursively sorts those. First, create a list of elements greater than a given value biggerlist :: Ord a => a -> [a] -> [a] biggerlist n xs = [x | x n] Likewise, create a list of elements less than or equal to a given value smallerlist :: Ord a => a -> [a] -> [a] smallerlist n xs = [x | x <- xs, x <= n]

Spring 2016 CSCE 314 – Programming Studio Example: quicksort (continued) Now, quicksort is straightforward: quicksort :: [a] -> [a] quicksort[] = [] quicksort (x:xs) = quicksort (smallerlist x xs) ++ [x] ++ quicksort (biggerlist x xs)

Spring 2016 CSCE 314 – Programming Studio Example: insert into ordered list insert :: Ord a => a -> [a] -> [a] insert x [] = [x] insert x (y:ys) | x <= y = x:y:ys | otherwise = y:insert x ys

Spring 2016 CSCE 314 – Programming Studio Example: Insertion sort Given the insert command, write insertion sort insort :: Ord a => [a] -> [a] insort [] = [] insort (x:xs) = insert x (insort xs)

Spring 2016 CSCE 314 – Programming Studio Additional notes Strings are just lists of characters So, all the list commands can be applied to strings Section 5.5 has an extended example of how to create, use, and crack the Caesar cipher You should read this section, try it yourself, and make sure you understand how it works! Ask questions if you have them, next class We will next be looking more closely at recursion next time