Haskell: Syntax in Functions

Slides:



Advertisements
Similar presentations
Functional Programming Lecture 10 - type checking.
Advertisements

Modern Programming Languages, 2nd ed.
0 PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
Introducing the Erlang Language Why Erlang?  Exemplifies the “you can have code and concurrency that is free from side effects…there is no other way”
0 PROGRAMMING IN HASKELL Chapter 3 - Types and Classes.
Using Types Slides thanks to Mark Jones. 2 Expressions Have Types: The type of an expression tells you what kind of value you might expect to see if you.
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
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.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
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?
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
A Second Look At ML 1. Outline Patterns Local variable definitions A sorting example 2.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Scripting Languages Diana Trandab ă ț Master in Computational Linguistics - 1 st year
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Data And Variables Chapter Names vs. Values Michael Jordan name (the letter sequence used to refer to something) value (the thing itself)
Validation using Regular Expressions. Regular Expression Instead of asking if user input has some particular value, sometimes you want to know if it follows.
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
Chapter SevenModern Programming Languages1 A Second Look At ML.
Haskell Chapter 4. Recursion  Like other languages  Base case  Recursive call  Author programs a number of built-in functions as examples.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
List Operations CSCE 314 Spring CSCE 314 – Programming Studio Tuple and List Patterns Pattern matching with wildcards for tuples fst (a, _) = a.
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
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)
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.
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}
Polymorphic Functions
Haskell Chapter 8.
CHAPTER 10 JAVA SCRIPT.
Recursion.
User-Written Functions
PROGRAMMING IN HASKELL
Types CSCE 314 Spring 2016.
dr Robert Kowalczyk WMiI UŁ
Theory of Computation Lecture 4: Programs and Computable Functions II
Haskell Chapter 2.
Lecture 2:Data Types, Functional Patterns, Recursion, Polymorphism
Exponents Scientific Notation
Chapter 2 Assignment and Interactive Input
A lightening tour in 45 minutes
Haskell Chapter 4.
EGR 2261 Unit 4 Control Structures I: Selection
Debugging and Random Numbers
Functional Programming
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
PROGRAMMING IN HASKELL
More Selections BIS1523 – Lecture 9.
Conditions and Ifs BIS1523 – Lecture 8.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
PROGRAMMING IN HASKELL
T. Jumana Abu Shmais – AOU - Riyadh
PROGRAMMING IN HASKELL
Type & Typeclass Syntax in function
CSCE 314: Programming Languages Dr. Dylan Shell
PROGRAMMING IN HASKELL
Fundamentals of Functional Programming
HIGHER ORDER FUNCTIONS
Introduction to Computer Science
Functional Programming
Functions and patterns
PROGRAMMING IN HASKELL
Validation using Regular Expressions
PROGRAMMING IN HASKELL
Class code for pythonroom.com cchsp2cs
Presentation transcript:

Haskell: Syntax in Functions Presentation and code examples: https://goo.gl/Q8fyUc Haskell: Syntax in Functions Bohdan Tokariev Using examples and some jokes from “Learn you a Haskell” book

FrienDly recap In Haskell we define function like this: So it’s sort of similar with JavaScript where you can do it in such manner: ES5: Or using ES6 arrow functions (please use them when you can): squared x = x * 2 var squared = function(x) { return x * 2 } let squared = (x) => x * 2;

datatype is valid for pattern matching EVERY datatype is valid for pattern matching It means you can use: Numbers Characters Lists Tuples Whatever

Pattern matching All you need to do is to declare separate function body and you’re ready to go Patterns will be checked from top to bottom and corresponding one will run his function lucky :: (Integral a) => a -> String lucky 7 = "LUCKY NUMBER SEVEN!" lucky x = "Sorry, you're out of luck, pal!"

Pattern matching You can create as many patterns as you want (it’s your life hey) IMPORTANT! Always include a catch-all pattern (in this case ”x”) so that our program doesn't crash if we get some unexpected input sayMe :: (Integral a) => a -> String   sayMe 1 = "One!"   sayMe 2 = "Two!"   sayMe 3 = "Three!"   sayMe 4 = "Four!"   sayMe 5 = "Five!"   sayMe x = "Not between 1 and 5"  

Pattern matching (now with tuples) If we (for some reason) want to add elements of two vectors we can do something like this: addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)   addVectors a b = (fst a + fst b, snd a + snd b)

Pattern matching (now with tuples) If we (for some reason) want to add elements of two vectors we can do something like this: But now lets use some pattern So if we, for example, type addVectors (2,2) (4,3) , the result should look like (6,5) addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)   addVectors a b = (fst a + fst b, snd a + snd b) MAGIC addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a)   addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)

Pattern matching (now with tuples) fst and snd extract the components of pairs. But what about triples? Well, there are no provided functions that do that but we can make our own. first :: (a, b, c) -> a   first (x, _, _) = x      second :: (a, b, c) -> b   second (_, y, _) = y   third :: (a, b, c) -> c   third (_, _, z) = z

Pattern matching (now with tuples) Also we can use patterns in list comprehensions In this case the result should be: [4,7,6,8,11,4] ghci> let xs = [(1,3), (4,3), (2,4), (5,3), (5,6), (3,1)]   ghci> [a+b | (a,b) <- xs]

Pattern matching (in lists) Since [1,2,3] is just syntactic sugar for 1:2:3:[], you can also use the former pattern. A pattern like x:xs will bind the head of the list to x and the rest of it to xs If you want to bind the first three elements to variables and the rest of the list to another variable, you can use something like x:y:z:zs

Pattern matching (in lists) With such knowledge we are able to implement our own head function And proceed even further with the function, which can describe our list head' :: [a] -> a head' [] = error "Can't call head on an empty list, dummy!" head' (x:_) = x tell :: (Show a) => [a] -> String tell [] = "The list is empty" tell (x:[]) = "The list has one element: " ++ show x tell (x:y:[]) = "The list has two elements: " ++ show x ++ " and " ++ show y tell (x:y:_) = "This list is long. The first two elements are: " ++ show x ++ " and " ++ show y

Pattern matching (in lists) If you add @ to your pattern you can assign a name to your list, so you can use it later Keeping in mind that strings are lists of characters we’re able to get a first letter from it With input capital "Haskell" the output should be: "The first letter of Haskell is H" capital :: String -> String   capital "" = "Empty string, whoops!"   capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x]

Guards! Guards are pretty similar to a basic “if/else if” statement, that is used in imperative languages, but looks a little more fancy With can see them in action in this implementation of max function Otherwise is an equivalent of else, where it equals True and catches everything max' :: (Ord a) => a -> a -> a   max' a b        | a > b     = a       | otherwise = b IMPORTANT! There is no need to put = before the |. Unless you want to get a compilation error of course.

Where (is my mind) Because we can’t create variables in function body, the where statement becomes handy, when there is a need in binding names bmiTell :: (RealFloat a) => a -> a -> String bmiTell weight height     | bmi <= 18.5 = "You're underweight, you emo!"     | bmi <= 25.0 = "You're supposedly normal."     | bmi <= 30.0 = "You're fat! Lose some weight, fatty!"     | otherwise   = "You're a whale, congratulations!"     where bmi = weight / height ^ 2

Where (is my mind) Another example is a function, that returns initials from provided name initials :: String -> String -> String   initials firstname lastname = [f] ++ ". " ++ [l] ++ "."       where (f:_) = firstname             (l:_) = lastname  IMPORTANT! Where statement needs to be indented (like in Python), because compiler will be confused about where this “where” belongs (pun intended)

Bear with me, only few slides left let bindings Let bindings let you bind to variables anywhere and are expressions themselves, but are very local, so they don't span across guards Here is a function that gives us a cylinder's surface area based on its height and radius cylinder :: (RealFloat a) => a -> a -> a   cylinder r h =      let sideArea = 2 * pi * r * h           topArea = pi * r ^2       in  sideArea + 2 * topArea

Case expressions Remember the custom head function that we did earlier? We can rebuild it using case of expression that is same as switch/case used everywhere else Both are completely interchangable head' :: [a] -> a   head' [] = error "No head for empty lists!"   head' (x:_) = x   head' :: [a] -> a head' xs = case xs of [] -> error "No head for empty lists!"                       (x:_) -> x

Thank you for your attention Link for presentation and examples: https://goo.gl/Q8fyUc Book chapter link: http://learnyouahaskell.com/syntax-in-functions