More Haskell Functions

Slides:



Advertisements
Similar presentations
15-Jan-15 More Haskell Functions Maybe, Either, List, Set, Map.
Advertisements

Haskell Chapter 7. Topics  Defining data types  Exporting types  Type parameters  Derived instances  Type synonyms  Either  Type classes  Not.
ML Lists.1 Standard ML Lists. ML Lists.2 Lists  A list is a finite sequence of elements. [3,5,9] ["a", "list" ] []  ML lists are immutable.  Elements.
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.
Haskell. 2 GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
Haskell Chapter 8. Input and Output  What are I/O actions?  How do I/O actions enable us to do I/O?  When are I/O actions actually performed?
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) Modules.
Advanced Functional Programming 2009 Ulf Norell (lecture by Jean-Philippe Bernardy)
1-Nov-15 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
0 PROGRAMMING IN HASKELL Chapter 9 - Higher-Order Functions, Functional Parsers.
1 Functional Programming Lecture 6 - Algebraic Data Types.
0 Functors in Haskell Adapted from material by Miran Lipovaca.
16-Nov-15 More Haskell Functions Maybe, Either, List, Set, Map.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Lee CSCE 314 TAMU 1 CSCE 314 Programming Languages Haskell: Higher-order Functions Dr. Hyunyoung Lee.
0 Modules in Haskell Adapted from material by Miran Lipovaca.
1 CS 457/557: Functional Languages Lists and Algebraic Datatypes Mark P Jones Portland State University.
1 Associative Containers Ordered Ordered Unordered UnorderedSets Maps as sets of pairs Set API Ex: Sieve of Eratosthenes Ex: Sieve of EratosthenesImplementation.
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,
Haskell Chapter 5, Part II. Topics  Review/More Higher Order Functions  Lambda functions  Folds.
Haskell. GHC and HUGS Haskell 98 is the current version of Haskell GHC (Glasgow Haskell Compiler, version 7.4.1) is the version of Haskell I am using.
1 PROGRAMMING IN HASKELL Lecture 2 Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources)
24-Jun-16 Haskell Dealing with impurity. Purity Haskell is a “pure” functional programming language Functions have no side effects Input/output is a side.
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.
6-Jul-16 Haskell II Functions and patterns. Data Types Int + - * / ^ even odd Float + - * / ^ sin cos pi truncate Char ord chr isSpace isUpper … Bool.
1 PROGRAMMING IN HASKELL Based on lecture notes by Graham Hutton The book “Learn You a Haskell for Great Good” (and a few other sources) Type declarations.
Advanced Functional Programming 2010
Haskell Chapter 8.
Haskell Chapter 7.
Types CSCE 314 Spring 2016.
More Haskell Functions
Functions and patterns
A lightening tour in 45 minutes
Haskell programming language.
PROGRAMMING IN HASKELL
Haskell.
More Haskell Functions
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Haskell Strings and Tuples
Computer Science 312 Haskell Lists 1.
PROGRAMMING IN HASKELL
Haskell Dealing with impurity 30-Nov-18.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
More Haskell Functions
PROGRAMMING IN HASKELL
Type & Typeclass Syntax in function
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Higher Order Functions
Haskell Modules Roshan Gunathilake.
Fundamentals of Functional Programming
topics mutable data structures
Haskell Dealing with impurity 8-Apr-19.
Records and Type Classes
Functions and patterns
PROGRAMMING IN HASKELL
Defining New Data Types
PROGRAMMING IN HASKELL
Functions and patterns
Computer Science 312 Making choices Tail Recursion
PROGRAMMING IN HASKELL
Haskell Dealing with impurity 29-May-19.
PROGRAMMING IN HASKELL
Haskell Dealing with impurity 28-Jun-19.
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
Records and Type Classes
Presentation transcript:

More Haskell Functions Maybe, Either, List, Set, Map 4-Apr-19

Maybe find takes a predicate and a list, and returns the first element that satisfies the predicate Example: find (> 4) [1..10] But what if there is no such element? find (> 40) [1..10] In such a case, Java would return null There’s nothing in the syntax that warns you this might happen Thus, you can get a NullPointerException In Haskell, find returns a Maybe find :: (a -> Bool) -> [a] -> Maybe a A Maybe can have the value Nothing or Just something find (>4) [1..10] Just 5 find (> 40) [1..10] Nothing This works well when combined with pattern matching

Either Either takes two types: Either a b buy :: String -> Int -> Either String Int buy item cost = if cost < 20 then Left ("Purchased " ++ item) else Right cost *Main> buy "lamp" 15 Left "Purchased lamp" *Main> buy "sofa" 300 Right 300

Modules A Haskell module is like a Java package A module contains functions, types, and typeclasses Unlike Java, there are a lot of name collisions, so modules often have to be imported in a qualified way To import into GHCi, use :m + module ... module To import into a program, use import module import module (f1,...,fn) will import only the named functions import module hiding (f1,...,fn) will import all but the named functions import qualified module imports the module; we call an imported function fn with module.fn import qualified module as M imports the module; we call an imported function fn with M.fn

Typeclasses A Haskell typeclass is like a Java interface--it tells what functions an object can support Some typeclasses and what they support: Eq -- == and /= Ord -- < <= >= > Num -- + - * / and others Show -- show (enables printing as a string) Read -- read (conversion from a string to something else) Functor -- fmap (enables mapping over things) Lists belong to the Functor typeclass Monad -- >>= >> return fail

Data.List I The standard Prelude imports many Data.List functions for us: map, filter, foldl, etc. intersperse :: a -> [a] -> [a] intersperse ' ' "hello"  "h e l l o” intercalate :: [a] -> [[a]] -> [a] intercalate " and " ["one", "two", "three"]  "one and two and three" transpose :: [[a]] -> [[a]] transpose [[1,2,3],[4,5,6]]  [[1,4],[2,5],[3,6]] take 5 (iterate (* 2) 1)  [1,2,4,8,16] take 5 (drop 5 (iterate (* 2) 1))  [32,64,128,256,512] take 5 $ drop 5 $ iterate (* 2) 1  [32,64,128,256,512] takeWhile (/= ' ') "Hello there"  "Hello” dropWhile (/= ' ') "Hello there"  " there"

Data.List II The following are especially helpful when dealing with text: span isLetter "one two three"  ("one"," two three") break isSpace "one two three"  ("one"," two three") words "Here are some words."  ["Here","are","some","words."] unwords $ words "Here are some words."  "Here are some words." lines "Roses are red\nViolets are blue"  ["Roses are red","Violets are blue"] unlines $ lines "Roses are red\nViolets are blue"  "Roses are red\nViolets are blue\n"

Data.Char Predicates: Conversions: isControl isSpace (any whitespace) isLower, isUpper isAlpha, isAlphaNum, isDigit isPunctuation and others Conversions: toUpper, toLower, toTitle digitToInt, intToDigit ord, chr

Data.Map Maps are constructed from lists of 2-tuples Not using a Map: *Main> let nums = [(1, "one"), (2, "two"), (3, "three"), (4, "four"), (5, "five")] *Main> lookup 3 nums Just "three" Using a Map: *Main> let dict = Map.fromList nums *Main> dict fromList [(1,"one"),(2,"two"),(3,"three"),(4,"four"),(5,"five")] *Main> :t Map.fromList Map.fromList :: (Ord k) => [(k, a)] -> Map.Map k a *Main> Map.lookup 3 dict Just "three" *Main> Map.lookup 7 dict Nothing

Map operations I Maps in Haskell are implemented with binary trees, not with hash tables Hence, keys must belong to the Ord typeclass Map.empty -- returns an empty map Map.null map -- tests if a map is empty Map.singleton key value -- returns a map with one key/value pair Map.fromList list -- given a list of 2-tuples, returns a map Note: Only the last value is kept if a key is repeated Map.insert key value map -- inserts a key/value pair Map.size map -- returns the number of key/value pairs Map.member key -- tests if the key is in the map Map.lookup key -- returns Just value or Nothing

Map operations II Map.map f map -- returns a map in which f has been applied to each value Map.filter f map -- returns a map containing only those key/value pairs for which f value is True Map.keys map -- returns a list of keys Map.elems map -- returns a list of values Map.toList map -- returns a list of (key, value) 2-tuples Map.fromListWith f list -- given a list of 2-tuples, returns a map; f is applied to combine duplicate values for the same key Map.insertWith f key value -- inserts the key/value pair into the map, using the function f to combine duplicate values for the same key

Sets in Haskell Sets, like Maps, are constructed from lists Like Maps, the import should be qualified to avoid name collisions: import qualified Data.Set as Set Set.fromList list -- returns a set created from a list (duplicates are removed) Set.toList set -- returns an ordered list from a set

Set operations Set.empty Set.null set Set.member value set Set.union set1 set2 Set.intersection set1 set2 Set.difference set1 set2 Set.size set Set.singleton value Set.insert value set Set.delete value set Set.map f set Set.filter f set

Compiling a Haskell program On UNIX (including Linux and Mac OS): Compile with ghc --make filename (omit the .hs) Run with ./filename On Windows: Set the PATH environment variable to something like C:\ghc\ghc-6.6\bin Compile with ghc inputfile -o outputfile Also works on a Mac compiling hello.hs results in hello.hi, hello.o, and main.exe Run with outputfile.exe Running as an interpreted program, without compiling: runhaskell filename.hs

The End