GHCi: Getting started (1A) Young Won Lim 6/3/17

Similar documents
GHCi: Getting started (1A) Young Won Lim 5/31/17

GHCi: Getting started (1A) Young Won Lim 5/26/17

Libraries (1A) Young Won Lim 6/5/17

Monad (1A) Young Won Lim 6/9/17

Monad (1A) Young Won Lim 6/21/17

Monad (1A) Young Won Lim 6/26/17

Monad (3A) Young Won Lim 8/9/17

Maybe Monad (3B) Young Won Lim 12/21/17

Maybe Monad (3B) Young Won Lim 1/3/18

Monad P1 : Several Monad Types (4A) Young Won Lim 2/13/19

Monad Background (3A) Young Won Lim 11/20/17

Background Operators (1E) Young Won Lim 7/7/18

Monad Background (3A) Young Won Lim 11/8/17

Haskell Overview III (3A) Young Won Lim 10/4/16

Monad Background (3A) Young Won Lim 11/18/17

Monad Background (3A) Young Won Lim 10/5/17

Standard prelude. Appendix A. A.1 Classes

Background Type Classes (1B) Young Won Lim 6/14/18

Polymorphism Overview (1A) Young Won Lim 2/20/18

Background Type Classes (1B) Young Won Lim 6/28/18

Haskell Overview IV (4A) Young Won Lim 10/13/16

Haskell Overview IV (4A) Young Won Lim 10/24/16

Haskell Overview II (2A) Young Won Lim 8/9/16

Side Effects (3B) Young Won Lim 11/23/17

Side Effects (3B) Young Won Lim 11/20/17

Side Effects (3B) Young Won Lim 11/27/17

Applicatives Comparisons (2C) Young Won Lim 3/6/18

State Monad (3D) Young Won Lim 8/31/17

State Monad (3D) Young Won Lim 9/25/17

Side Effects (3A) Young Won Lim 1/13/18

IO Monad (3C) Young Won Lim 8/23/17

Background Expressions (1D) Young Won Lim 7/7/18

Haskell An Introduction

Haskell Overview II (2A) Young Won Lim 8/23/16

Introduction to Haskell

CS 320: Concepts of Programming Languages

Programming Paradigms

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

Background Constructors (1A) Young Won Lim 7/9/18

Haskell Types COMP360

Haskell Modules. Input and Output. Urtė Zubkaitė

IO Monad (3D) Young Won Lim 1/18/18

IO Monad (3C) Young Won Lim 1/6/18

Box-and-arrow Diagrams

Haskell Scripts. Yan Huang

Logic Haskell Exercises

Solution sheet 1. Introduction. Exercise 1 - Types of values. Exercise 2 - Constructors

CSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.

CS 11 Haskell track: lecture 1

Practical Haskell. An introduction to functional programming. July 21, Practical Haskell. Juan Pedro Villa-Isaza. Introduction.

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

Background Constructors (1A) Young Won Lim 6/30/18

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming

According to Larry Wall (designer of PERL): a language by geniuses! for geniuses. Lecture 7: Haskell. Haskell 98. Haskell (cont) - Type-safe!

Haskell Overview II (2A) Young Won Lim 9/26/16

Overloading, Type Classes, and Algebraic Datatypes

Background Constructors (1A) Young Won Lim 7/5/18

CS 440: Programming Languages and Translators, Spring 2019 Mon 2/4

Monad Overview (3B) Young Won Lim 1/16/18

Background Constructors (1A) Young Won Lim 1/22/18

CSc 372. Comparative Programming Languages. 8 : Haskell Function Examples. Department of Computer Science University of Arizona

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

INTRODUCTION TO HASKELL

Programming in Haskell Aug Nov 2015

State Monad Examples (6C) Young Won Lim 9/26/18

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Haskell Making Our Own Types and Typeclasses

State Monad Examples (6C) Young Won Lim 9/22/18

Haskell 101. (Version 1 (July 18, 2012)) Juan Pedro Villa Isaza

Haskell through HUGS THE BASICS

Haskell Types, Classes, and Functions, Currying, and Polymorphism

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

State Monad Example (3H) Young Won Lim 2/16/18

INDEX. Symbols & Numbers. Learn You a Haskell for Great Good! 2011 by Miran Lipovača

A Sudoku Solver (1A) Richard Bird Implementation. Young Won Lim 11/15/16

Documentation for the Idris Language. Version 1.0

Functional Programming and Haskell

EDAF40. 2nd June :00-19:00. WRITE ONLY ON ONE SIDE OF THE PAPER - the exams will be scanned in and only the front/ odd pages will be read.

A Sudoku Solver Pruning (3A)

Advanced Topics in Programming Languages Lecture 2 - Introduction to Haskell

Functional Programming

The List Datatype. CSc 372. Comparative Programming Languages. 6 : Haskell Lists. Department of Computer Science University of Arizona

(ii) Define a function ulh that takes a list xs, and pairs each element with all other elements in xs.

Haskell Modules. Stéphane Vialette. November 20, LIGM, Université Paris-Est Marne-la-Vallée

Learn You a Haskell for Great Good!

Principles of Programming Languages (H)

Background Functions (1C) Young Won Lim 5/26/18

CS 360: Programming Languages Lecture 10: Introduction to Haskell

User-Defined Algebraic Data Types

Functional Programming for Logicians - Lecture 1

Haskell Programs. Haskell Fundamentals. What are Types? Some Very Basic Types. Types are very important in Haskell:

Set Haskell Exercises

Documentation for the Idris Language. Version 0.99

CSc 372 Comparative Programming Languages

A general introduction to Functional Programming using Haskell

The Idris Tutorial. Release The Idris Community

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

Operators (2A) Young Won Lim 10/2/13

Type system. Type theory. Haskell type system. EDAN40: Functional Programming Types and Type Classes (revisited)

CSc 520. Principles of Programming Languages 11: Haskell Basics

Transcription:

GHCi: Getting started (1A)

Copyright (c) 2016-2017 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License". Please send corrections (or suggestions) to youngwlim@hotmail.com. This document was produced by using OpenOffice.

Based on Haskell in 5 steps https://wiki.haskell.org/haskell_in_5_steps 3

Interpreter GHCi young@mntsys-bb1 ~ $ ghci GHCi, version 7.10.3: http://www.haskell.org/ghc/ :? for help Prelude> "hello, world!" "hello, world!" Prelude> putstrln "hello, world!" hello, world! https://wiki.haskell.org/learn_haskell_in_10_minutes 4

Function Prelude> let fac n = if n == 0 then 1 else n * fac (n-1) Prelude> fac 5 120 Prelude> fac 2 2 Prelude> fac 3 6 Prelude> fac 4 24 Prelude> https://wiki.haskell.org/learn_haskell_in_10_minutes 5

Compiler GHC young@mntsys-bb1 ~ $ ghc -o hello hello.hs [1 of 1] Compiling Main ( hello.hs, hello.o ) Linking hello... young@mntsys-bb1 ~ $./hello hello, world! young@mntsys-bb1 ~ $ cat hello.hs main = putstrln "hello, world!" https://wiki.haskell.org/learn_haskell_in_10_minutes 6

Layout t.hs main = do putstrln "Type an integer :?" x <- readln if even x then putstrln "even number" else putstrln "odd number" the first non-space character after do. every line that starts in the same column as that p is in the do block If you indent more, it is the nested block in do If you indent less, it is an end of the do block. ghc t.hs./t ghc o run t.hs./t 7

Multi-line in GHCi ghci multi-line Prelude> :{ Prelude main = do { putstrln "Type an integer: "; x<-readln; Prelude if even x then putstrln "even" else putstrln "odd"; } Prelude :} https://wiki.haskell.org/learn_haskell_in_10_minutes 8

Types Int Integer Float Double Rational an integer with at least 30 bits of precision. an integer with unlimited precision. a single precision floating point number. a double precision floating point number. a fraction type, with no rounding error. Types and Class Types start with capital letters Variables start with lower case letters Declaring a type Asking which type :: type :t something https://wiki.haskell.org/learn_haskell_in_10_minutes 9

Type Classes Prelude> 3 :: Int 3 Prelude> 3 :: Float 3.0 Prelude> 4 :: Double 4.0 Prelude> 2 :: Integer 2 Prelude> :t 3 3 :: Num a => a 3 can be used as any numeric type Prelude> :t 2.0 2.0 :: Fractional a => a 2.0 can be used as any fractional type Prelude> :t gcd 15 20 gcd 15 20 :: Integral a => a Prelude> :t True True :: Bool Prelude> :t 'A' 'A' :: Char class constraint (Num t) => (Fractional t) => (Integral t) => gcd 15 20 can be used as any integral type the type t is constrained by the context (Num t), (Fractional t), (Integral t) the types of t must be Num type class the types of t must be Fractional type class the types of t must be Integral type class https://wiki.haskell.org/learn_haskell_in_10_minutes 10

Type Classes Int Integer Float Double Rational Instances of Integral type Instances of Fractional type Instances of Num type Type Class : a set of type (instances) Instances of Num type Int Integer Float Double Rational Instances of Integral type Instances of Fractional type https://wiki.haskell.org/learn_haskell_in_10_minutes 11

Lists and Tuples Lists multiple values of the same type Strings lists of characters. Tuples a fixed number of values, which can have different types. The : operator appends an item to the beginning of a list Zip : two lists into a list of tuples. https://wiki.haskell.org/learn_haskell_in_10_minutes 12

Functions [1.. 10] map (+ 2) [1.. 10] filter (> 2) [1.. 10] [1,2,3,4,5,6,7,8,9,10] [3,4,5,6,7,8,9,10,11,12] [3,4,5,6,7,8,9,10] fst (1, 2) snd (1, 2) map fst [(1, 2), (3, 4), (5, 6)] 1 2 [1,3,5] fst (1, 2, 3) snd (1, 2, 3) https://wiki.haskell.org/learn_haskell_in_10_minutes 13

Functions my_sum m n = m+n main = do putstrln "Give two numbers: " x <- readln y <- readln print (my_sum x y) Give two numbers: 10 20 30 https://wiki.haskell.org/learn_haskell_in_10_minutes 14

Convenient Syntax secstoweeks secs =let perminute = 60 perhour = 60 * perminute perday = 24 * perhour perweek = 7 * perday in secs / perweek classify age = case age of 0 -> "newborn" 1 -> "infant" 2 -> "toddler" _ -> "senior citizen" https://wiki.haskell.org/learn_haskell_in_10_minutes 15

Using Libraries import Prelude hiding (lookup) import Data.Map employeedept = fromlist([("john","sales"), ("Bob","IT")]) deptcountry = fromlist([("it","usa"), ("Sales","France")]) countrycurrency = fromlist([("usa", "Dollar"), ("France", "Euro")]) employeecurrency :: String -> Maybe String employeecurrency name = do dept <- lookup name employeedept country <- lookup dept deptcountry lookup country countrycurrency main = do putstrln $ "John's currency: " ++ (show (employeecurrency "John")) putstrln $ "Pete's currency: " ++ (show (employeecurrency "Pete")) https://downloads.haskell.org/~ghc/latest/docs/html/libraries/containers-0.5.7.1/data-map-lazy.html 16

fromlist (1) fromlist :: Eq key => (key -> Int32) -> [(key, val)] -> IO (HashTable key val) base Data.HashTable Convert a list of key/value pairs into a hash table. Equality on keys is taken from the Eq instance for the key type. fromlist :: [(Key, a)] -> IntMap a containers Data.IntMap.Strict, containers Data.IntMap.Lazy O(n*min(n,W)). Create a map from a list of key/value pairs. > fromlist [] == empty > fromlist [(5,"a"), (3,"b"), (5, "c")] == fromlist [(5,"c"), (3,"b")] > fromlist [(5,"c"), (3,"b"), (5, "a")] == fromlist [(5,"a"), (3,"b")] fromlist :: [Key] -> IntSet containers Data.IntSet O(n*min(n,W)). Create a set from a list of integers. fromlist :: [a] -> Seq a containers Data.Sequence O(n). Create a sequence from a finite list of elements. There is a function tolist in the opposite direction for all instances of the Foldable class, including Seq. https://www.haskell.org/hoogle/?hoogle=fromlist 17

fromlist (2) fromlist :: Ord a => [a] -> Set a containers Data.Set O(n*log n). Create a set from a list of elements. If the elemens are ordered, linear-time implementation is used, with the performance equal to fromdistinctasclist. fromlist :: Ord k => [(k, a)] -> Map k a containers Data.Map.Lazy, containers Data.Map.Strict O(n*log n). Build a map from a list of key/value pairs. See also fromasclist. If the list contains more than one value for the same key, the last value for the key is retained. If the keys of the list are ordered, linear-time implementation is used, with the performance equal to fromdistinctasclist. > fromlist [] == empty > fromlist [(5,"a"), (3,"b"), (5, "c")] == fromlist [(5,"c"), (3,"b")] > fromlist [(5,"c"), (3,"b"), (5, "a")] == fromlist [(5,"a"), (3,"b")] https://www.haskell.org/hoogle/?hoogle=fromlist 18

lookup (1) lookup :: Eq a => a -> [(a, b)] -> Maybe b base Prelude, base Data.List lookup key assocs looks up a key in an association list. lookup :: HashTable key val -> key -> IO (Maybe val) base Data.HashTable Looks up the value of a key in the hash table. lookup :: Key -> IntMap a -> Maybe a containers Data.IntMap.Strict, containers Data.IntMap.Lazy O(min(n,W)). Lookup the value at a key in the map. See also lookup. lookup :: Ord k => k -> Map k a -> Maybe a containers Data.Map.Lazy, containers Data.Map.Strict O(log n). Lookup the value at a key in the map. The function will return the corresponding value as (Just value), or Nothing if the key isn't in the map. An example of using lookup: https://www.haskell.org/hoogle/?hoogle=fromlist 19

lookup (2) > import Prelude hiding (lookup) > import Data.Map > > employeedept = fromlist( [ ("John", "Sales"), ("Bob", "IT") ] ) > deptcountry = fromlist( [ ("IT", "USA"), ("Sales", "France") ] ) > countrycurrency = fromlist( [ ("USA", "Dollar"), ("France", "Euro") ] ) > > employeecurrency :: String -> Maybe String > employeecurrency name = do > dept <- lookup name employeedept > country <- lookup dept deptcountry > lookup country countrycurrency > > main = do > putstrln $ "John's currency: " ++ (show (employeecurrency "John")) > putstrln $ "Pete's currency: " ++ (show (employeecurrency "Pete")) The output of this program: > John's currency: Just "Euro" > Pete's currency: Nothing https://www.haskell.org/hoogle/?hoogle=fromlist 20

elem elem :: Eq a => a -> [a] -> Bool base Prelude, base Data.List elem is the list membership predicate, usually written in infix form, e.g., x `elem` xs. For the result to be False, the list must be finite; True, however, results from an element equal to x found at a finite index of a finite or infinite list. 1 `elem` [1, 2, 4] -- True 2 `elem` [1, 2, 4] -- True 3 `elem` [1, 2, 4] -- False https://www.haskell.org/hoogle/?hoogle=fromlist 21

Generator let removelower x=[c c<-x, c `elem` ['A'..'Z']] a list comprehension [c c<-x, c `elem` ['A'..'Z']] c <- x is a generator c is a pattern to be matched from the elements of the list x to be successively bound to the elements of the input list x c `elem` ['A'..'Z'] is a predicate which is applied to each successive binding of c inside the comprehension an element of the input only appears in the output list if it passes this predicate. https://stackoverflow.com/questions/35198897/does-mean-assigning-a-variable-in-haskell 22

Assignment in Haskell Assignment in Haskell : declaration with initialization: You declare a variable; Haskell doesn't allow uninitialized variables, so an initial value must be supplied in the declaration There's no mutation, so the value given in the declaration will be the only value for that variable throughout its scope. https://stackoverflow.com/questions/35198897/does-mean-assigning-a-variable-in-haskell 23

Assignment in Haskell filter (`elem` ['A'.. 'Z']) x [c c <- x] do c <- x return c x >>= \c -> return c x >>= return https://stackoverflow.com/questions/35198897/does-mean-assigning-a-variable-in-haskell 24

Monad Class Function >>= & >> both >>= and >> are functions from the Monad class. >>= passes the result of the expression on the left as an argument to the expression on the right, in a way that respects the context the argument and function use >> is used to order the evaluation of expressions within some context; it makes evaluation of the right depend on the evaluation of the left https://www.quora.com/what-do-the-symbols-and-mean-in-haskell 25

Monad List Comprehension Examples [x*2 x<-[1..10], odd x] do x <- [1..10] if odd x then [x*2] else [] [1..10] >>= (\x -> if odd x then [x*2] else []) https://stackoverflow.com/questions/44965/what-is-a-monad 26

Monad I/O Examples do putstrln "What is your name?" name <- getline putstrln ("Welcome, " ++ name ++ "!") https://stackoverflow.com/questions/44965/what-is-a-monad 27

Monad A Parser Example parseexpr = parsestring < > parsenumber parsestring = do char '"' x <- many (noneof "\"") char '"' return (StringValue x) parsenumber = do num <- many1 digit return (NumberValue (read num)) https://stackoverflow.com/questions/44965/what-is-a-monad 28

Monad Asynchronous Examples let AsyncHttp(url:string) = async { let req = WebRequest.Create(url) let! rsp = req.getresponseasync() use stream = rsp.getresponsestream() use reader = new System.IO.StreamReader(stream) return reader.readtoend() } https://stackoverflow.com/questions/44965/what-is-a-monad 29

References [1] ftp://ftp.geoinfo.tuwien.ac.at/navratil/haskelltutorial.pdf [2] https://www.umiacs.umd.edu/~hal/docs/daume02yaht.pdf