SlideShare a Scribd company logo
1
PROGRAMMING IN HASKELL
Chapter 2 - First Steps
2
Glasgow Haskell Compiler
GHC is the leading implementation of Haskell,
and comprises a compiler and interpreter;
The interactive nature of the interpreter makes it
well suited for teaching and prototyping;
GHC is freely available from:
www.haskell.org/platform
3
Starting GHC
% ghci
GHCi, version 7.4.1: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude>
The GHC interpreter can be started from the Unix
command prompt % by simply typing ghci:
4
The GHCi prompt > means that the interpreter is
ready to evaluate an expression.
For example:
> 2+3*4
14
> (2+3)*4
20
> sqrt (3^2 + 4^2)
5.0
5
The Standard Prelude
Haskell comes with a large number of standard
library functions. In addition to the familiar
numeric functions such as + and *, the library
also provides many useful functions on lists.
Select the first element of a list:
> head [1,2,3,4,5]
1
6
Remove the first element from a list:
> tail [1,2,3,4,5]
[2,3,4,5]
Select the nth element of a list:
> [1,2,3,4,5] !! 2
3
Select the first n elements of a list:
> take 3 [1,2,3,4,5]
[1,2,3]
7
Remove the first n elements from a list:
> drop 3 [1,2,3,4,5]
[4,5]
Calculate the length of a list:
> length [1,2,3,4,5]
5
Calculate the sum of a list of numbers:
> sum [1,2,3,4,5]
15
8
Calculate the product of a list of numbers:
> product [1,2,3,4,5]
120
Append two lists:
> [1,2,3] ++ [4,5]
[1,2,3,4,5]
Reverse a list:
> reverse [1,2,3,4,5]
[5,4,3,2,1]
9
Function Application
In mathematics, function application is denoted
using parentheses, and multiplication is often
denoted using juxtaposition or space.
f(a,b) + c d
Apply the function f to a and b, and add
the result to the product of c and d.
10
In Haskell, function application is denoted using
space, and multiplication is denoted using *.
f a b + c*d
As previously, but in Haskell syntax.
11
Moreover, function application is assumed to have
higher priority than all other operators.
f a + b
Means (f a) + b, rather than f (a + b).
12
Examples
Mathematics Haskell
f(x)
f(x,y)
f(g(x))
f(x,g(y))
f(x)g(y)
f x
f x y
f (g x)
f x (g y)
f x * g y
13
Haskell Scripts
As well as the functions in the standard library,
you can also define your own functions;
New functions are defined within a script, a text
file comprising a sequence of definitions;
By convention, Haskell scripts usually have a
.hs suffix on their filename. This is not
mandatory, but is useful for identification
purposes.
14
My First Script
double x = x + x
quadruple x = double (double x)
When developing a Haskell script, it is useful to
keep two windows open, one running an editor for
the script, and the other running GHCi.
Start an editor, type in the following two function
definitions, and save the script as test.hs:
15
% ghci test.hs
Leaving the editor open, in another window start up
GHCi with the new script:
> quadruple 10
40
> take (double 2) [1,2,3,4,5,6]
[1,2,3,4]
Now both the standard library and the file test.hs
are loaded, and functions from both can be used:
16
factorial n = product [1..n]
average ns = sum ns `div` length ns
Leaving GHCi open, return to the editor, add the
following two definitions, and resave:
div is enclosed in back quotes, not forward;
x `f` y is just syntactic sugar for f x y.
Note:
17
> :reload
Reading file "test.hs"
> factorial 10
3628800
> average [1,2,3,4,5]
3
GHCi does not automatically detect that the script
has been changed, so a reload command must be
executed before the new definitions can be used:
18
Naming Requirements
Function and argument names must begin with
a lower-case letter. For example:
myFun fun1 arg_2 x’
By convention, list arguments usually have an s
suffix on their name. For example:
xs ns nss
19
The Layout Rule
In a sequence of definitions, each definition must
begin in precisely the same column:
a = 10
b = 20
c = 30
a = 10
b = 20
c = 30
a = 10
b = 20
c = 30
20
means
The layout rule avoids the need for explicit syntax
to indicate the grouping of definitions.
a = b + c
where
b = 1
c = 2
d = a * 2
a = b + c
where
{b = 1;
c = 2}
d = a * 2
implicit grouping explicit grouping
21
Useful GHCi Commands
Command Meaning
:load name load script name
:reload reload current script
:edit name edit script name
:edit edit current script
:type expr show type of expr
:? show all commands
:quit quit GHCi
22
Exercises
N = a ’div’ length xs
where
a = 10
xs = [1,2,3,4,5]
Try out slides 2-8 and 14-17 using GHCi.
Fix the syntax errors in the program below,
and test your solution using GHCi.
(1)
(2)
23
Show how the library function last that selects
the last element of a list can be defined using
the functions introduced in this lecture.
(3)
Similarly, show how the library function init
that removes the last element from a list can
be defined in two different ways.
(5)
Can you think of another possible definition?(4)

More Related Content

What's hot

C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
Programming Homework Help
 
week-12x
week-12xweek-12x
Programming Homework Help
Programming Homework Help Programming Homework Help
Programming Homework Help
Programming Homework Help
 
LCDS - State Presentation
LCDS - State PresentationLCDS - State Presentation
LCDS - State Presentation
Ruochun Tzeng
 
Php questions and answers
Php questions and answersPhp questions and answers
Php questions and answers
Deepika joshi
 
UNIT 4-HEADER FILES IN C
UNIT 4-HEADER FILES IN CUNIT 4-HEADER FILES IN C
UNIT 4-HEADER FILES IN C
Raj vardhan
 
Function
FunctionFunction
Function
venkatme83
 
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
Muhammad Ulhaque
 
Large Scale JavaScript with TypeScript
Large Scale JavaScript with TypeScriptLarge Scale JavaScript with TypeScript
Large Scale JavaScript with TypeScript
Oliver Zeigermann
 
Maintainable go
Maintainable goMaintainable go
Maintainable go
Yu-Shuan Hsieh
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
Maxim Zaks
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++
Patrick Viafore
 
Oop1
Oop1Oop1
Data Structure - 2nd Study
Data Structure - 2nd StudyData Structure - 2nd Study
Data Structure - 2nd Study
Chris Ohk
 
Scalability comparison: Traditional fork-join-based parallelism vs. Goroutine...
Scalability comparison: Traditional fork-join-based parallelism vs. Goroutine...Scalability comparison: Traditional fork-join-based parallelism vs. Goroutine...
Scalability comparison: Traditional fork-join-based parallelism vs. Goroutine...
Artjom Simon
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python Programmers
Appier
 
C language header files
C language header filesC language header files
C language header files
marar hina
 
C++11
C++11C++11
C++11
ppd1961
 
C++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLESC++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLES
Farhan Ab Rahman
 
Devel::hdb debugger talk
Devel::hdb debugger talkDevel::hdb debugger talk
Devel::hdb debugger talk
abrummett
 

What's hot (20)

C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
week-12x
week-12xweek-12x
week-12x
 
Programming Homework Help
Programming Homework Help Programming Homework Help
Programming Homework Help
 
LCDS - State Presentation
LCDS - State PresentationLCDS - State Presentation
LCDS - State Presentation
 
Php questions and answers
Php questions and answersPhp questions and answers
Php questions and answers
 
UNIT 4-HEADER FILES IN C
UNIT 4-HEADER FILES IN CUNIT 4-HEADER FILES IN C
UNIT 4-HEADER FILES IN C
 
Function
FunctionFunction
Function
 
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
 
Large Scale JavaScript with TypeScript
Large Scale JavaScript with TypeScriptLarge Scale JavaScript with TypeScript
Large Scale JavaScript with TypeScript
 
Maintainable go
Maintainable goMaintainable go
Maintainable go
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
Lambda Expressions in C++
Lambda Expressions in C++Lambda Expressions in C++
Lambda Expressions in C++
 
Oop1
Oop1Oop1
Oop1
 
Data Structure - 2nd Study
Data Structure - 2nd StudyData Structure - 2nd Study
Data Structure - 2nd Study
 
Scalability comparison: Traditional fork-join-based parallelism vs. Goroutine...
Scalability comparison: Traditional fork-join-based parallelism vs. Goroutine...Scalability comparison: Traditional fork-join-based parallelism vs. Goroutine...
Scalability comparison: Traditional fork-join-based parallelism vs. Goroutine...
 
Basic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python ProgrammersBasic C++ 11/14 for Python Programmers
Basic C++ 11/14 for Python Programmers
 
C language header files
C language header filesC language header files
C language header files
 
C++11
C++11C++11
C++11
 
C++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLESC++ ARRAY WITH EXAMPLES
C++ ARRAY WITH EXAMPLES
 
Devel::hdb debugger talk
Devel::hdb debugger talkDevel::hdb debugger talk
Devel::hdb debugger talk
 

Similar to Chapter2 Haskell

chapter2.ppt
chapter2.pptchapter2.ppt
chapter2.ppt
ssuser54d1db
 
Haskell
HaskellHaskell
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
Angelo Corsaro
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...
PVS-Studio
 
Matlab functions
Matlab functionsMatlab functions
Matlab functions
pramodkumar1804
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
Will Livengood
 
A05
A05A05
A05
lksoo
 
ANSI C Macros
ANSI C MacrosANSI C Macros
ANSI C Macros
Srikrishnan Suresh
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
HalaiHansaika
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
Bryan O'Sullivan
 
List-based Monadic Computations for Dynamically Typed Languages (Python version)
List-based Monadic Computations for Dynamically Typed Languages (Python version)List-based Monadic Computations for Dynamically Typed Languages (Python version)
List-based Monadic Computations for Dynamically Typed Languages (Python version)
Wim Vanderbauwhede
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
Devnology
 
Build Systems with autoconf, automake and libtool [updated]
Build Systems with autoconf, automake and libtool [updated]Build Systems with autoconf, automake and libtool [updated]
Build Systems with autoconf, automake and libtool [updated]
Benny Siegert
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
ReKruiTIn.com
 
CPP Assignment Help
CPP Assignment HelpCPP Assignment Help
CPP Assignment Help
C++ Homework Help
 
Introduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageIntroduction to GNU Make Programming Language
Introduction to GNU Make Programming Language
Shih-Hsiang Lin
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
Johan Tibell
 
Algorithm2e package for Latex
Algorithm2e package for LatexAlgorithm2e package for Latex
Algorithm2e package for Latex
Chris Lee
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic Languages
Wim Vanderbauwhede
 

Similar to Chapter2 Haskell (20)

chapter2.ppt
chapter2.pptchapter2.ppt
chapter2.ppt
 
Haskell
HaskellHaskell
Haskell
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...
 
Matlab functions
Matlab functionsMatlab functions
Matlab functions
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 
A05
A05A05
A05
 
ANSI C Macros
ANSI C MacrosANSI C Macros
ANSI C Macros
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
List-based Monadic Computations for Dynamically Typed Languages (Python version)
List-based Monadic Computations for Dynamically Typed Languages (Python version)List-based Monadic Computations for Dynamically Typed Languages (Python version)
List-based Monadic Computations for Dynamically Typed Languages (Python version)
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
Build Systems with autoconf, automake and libtool [updated]
Build Systems with autoconf, automake and libtool [updated]Build Systems with autoconf, automake and libtool [updated]
Build Systems with autoconf, automake and libtool [updated]
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
CPP Assignment Help
CPP Assignment HelpCPP Assignment Help
CPP Assignment Help
 
Introduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageIntroduction to GNU Make Programming Language
Introduction to GNU Make Programming Language
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Algorithm2e package for Latex
Algorithm2e package for LatexAlgorithm2e package for Latex
Algorithm2e package for Latex
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic Languages
 

Recently uploaded

CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
architagupta876
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
Mahmoud Morsy
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
sachin chaurasia
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
Nada Hikmah
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
UReason
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 

Recently uploaded (20)

CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
Certificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi AhmedCertificates - Mahmoud Mohamed Moursi Ahmed
Certificates - Mahmoud Mohamed Moursi Ahmed
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.The Python for beginners. This is an advance computer language.
The Python for beginners. This is an advance computer language.
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Curve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods RegressionCurve Fitting in Numerical Methods Regression
Curve Fitting in Numerical Methods Regression
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
Data Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason WebinarData Driven Maintenance | UReason Webinar
Data Driven Maintenance | UReason Webinar
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 

Chapter2 Haskell

  • 2. 2 Glasgow Haskell Compiler GHC is the leading implementation of Haskell, and comprises a compiler and interpreter; The interactive nature of the interpreter makes it well suited for teaching and prototyping; GHC is freely available from: www.haskell.org/platform
  • 3. 3 Starting GHC % ghci GHCi, version 7.4.1: http://www.haskell.org/ghc/ :? for help Loading package ghc-prim ... linking ... done. Loading package integer-gmp ... linking ... done. Loading package base ... linking ... done. Prelude> The GHC interpreter can be started from the Unix command prompt % by simply typing ghci:
  • 4. 4 The GHCi prompt > means that the interpreter is ready to evaluate an expression. For example: > 2+3*4 14 > (2+3)*4 20 > sqrt (3^2 + 4^2) 5.0
  • 5. 5 The Standard Prelude Haskell comes with a large number of standard library functions. In addition to the familiar numeric functions such as + and *, the library also provides many useful functions on lists. Select the first element of a list: > head [1,2,3,4,5] 1
  • 6. 6 Remove the first element from a list: > tail [1,2,3,4,5] [2,3,4,5] Select the nth element of a list: > [1,2,3,4,5] !! 2 3 Select the first n elements of a list: > take 3 [1,2,3,4,5] [1,2,3]
  • 7. 7 Remove the first n elements from a list: > drop 3 [1,2,3,4,5] [4,5] Calculate the length of a list: > length [1,2,3,4,5] 5 Calculate the sum of a list of numbers: > sum [1,2,3,4,5] 15
  • 8. 8 Calculate the product of a list of numbers: > product [1,2,3,4,5] 120 Append two lists: > [1,2,3] ++ [4,5] [1,2,3,4,5] Reverse a list: > reverse [1,2,3,4,5] [5,4,3,2,1]
  • 9. 9 Function Application In mathematics, function application is denoted using parentheses, and multiplication is often denoted using juxtaposition or space. f(a,b) + c d Apply the function f to a and b, and add the result to the product of c and d.
  • 10. 10 In Haskell, function application is denoted using space, and multiplication is denoted using *. f a b + c*d As previously, but in Haskell syntax.
  • 11. 11 Moreover, function application is assumed to have higher priority than all other operators. f a + b Means (f a) + b, rather than f (a + b).
  • 13. 13 Haskell Scripts As well as the functions in the standard library, you can also define your own functions; New functions are defined within a script, a text file comprising a sequence of definitions; By convention, Haskell scripts usually have a .hs suffix on their filename. This is not mandatory, but is useful for identification purposes.
  • 14. 14 My First Script double x = x + x quadruple x = double (double x) When developing a Haskell script, it is useful to keep two windows open, one running an editor for the script, and the other running GHCi. Start an editor, type in the following two function definitions, and save the script as test.hs:
  • 15. 15 % ghci test.hs Leaving the editor open, in another window start up GHCi with the new script: > quadruple 10 40 > take (double 2) [1,2,3,4,5,6] [1,2,3,4] Now both the standard library and the file test.hs are loaded, and functions from both can be used:
  • 16. 16 factorial n = product [1..n] average ns = sum ns `div` length ns Leaving GHCi open, return to the editor, add the following two definitions, and resave: div is enclosed in back quotes, not forward; x `f` y is just syntactic sugar for f x y. Note:
  • 17. 17 > :reload Reading file "test.hs" > factorial 10 3628800 > average [1,2,3,4,5] 3 GHCi does not automatically detect that the script has been changed, so a reload command must be executed before the new definitions can be used:
  • 18. 18 Naming Requirements Function and argument names must begin with a lower-case letter. For example: myFun fun1 arg_2 x’ By convention, list arguments usually have an s suffix on their name. For example: xs ns nss
  • 19. 19 The Layout Rule In a sequence of definitions, each definition must begin in precisely the same column: a = 10 b = 20 c = 30 a = 10 b = 20 c = 30 a = 10 b = 20 c = 30
  • 20. 20 means The layout rule avoids the need for explicit syntax to indicate the grouping of definitions. a = b + c where b = 1 c = 2 d = a * 2 a = b + c where {b = 1; c = 2} d = a * 2 implicit grouping explicit grouping
  • 21. 21 Useful GHCi Commands Command Meaning :load name load script name :reload reload current script :edit name edit script name :edit edit current script :type expr show type of expr :? show all commands :quit quit GHCi
  • 22. 22 Exercises N = a ’div’ length xs where a = 10 xs = [1,2,3,4,5] Try out slides 2-8 and 14-17 using GHCi. Fix the syntax errors in the program below, and test your solution using GHCi. (1) (2)
  • 23. 23 Show how the library function last that selects the last element of a list can be defined using the functions introduced in this lecture. (3) Similarly, show how the library function init that removes the last element from a list can be defined in two different ways. (5) Can you think of another possible definition?(4)