functional programming seminar (haskell)
TRANSCRIPT
Functional Programming
Seminar (Haskell)- BIKRAM THAPA (245066)
Today’s Seminar Contents
A) Introduction To Functional Programming And Haskell, Features, Application
B) Getting Started With Haskell, Prerequisites
C) Types And Type Classes
Quick Review of Functional Programming
Programming paradigm that treats computation as evaluation of mathematical functions.
Avoids change of states and mutable data.
The output value of function only depends on the arguments that are input to functions,
same output if function is called twice.
One of the main idea is eliminating side effects
Roots back from the lambda calculus since 1930
Many functional programming languages based on lambda calculus principles
Purely functional PL are Largely emphasized in academic learning rather than commercial development however semi function languages have been commonly used in industrial software development.
Eg. Lips, fp, ML Haskell etc.
Why functional programming
A journal By John Hughes http://worrydream.com/refs/Hughes-WhyFunctionalProgrammingMatters.pdf
Based on the original source of “Chalmers memo”
From “Research Topics in Functional Programming” ed. D. Turner, Addison-Wesley, 1990,
Few questions –How can we cope with the size and complexity of modern computer programs?How can we reduce the time and cost of program development?How to be confident that finished programs work correctly?
Approaches – Design new language that supportsPrograms can be written clearly, concisely and at high level of abstraction.Supports reusable software components.Rapid prototyping and powerful problem solving.Modularity support.
So functional programming evolves from these concepts.
Java
sum= 0;
for (i = 1; i 10; ++i)
sum= sum+i;
Functional style
Sum[1..10]
Historical Background 1930, Alonzo Church developed the lambda calculus, a simple but
powerful theory of functions.
1950, John McCarthy developed Lisp, the first functional language, with some influences from the lambda calculus, but retaining variable assignments.
1960, Peter Landin developed ISWIM, the first pure functional language, based strongly on the lambda calculus, with no assignments.
1970, John Backus developed FP, a functional language that emphasizes higher-order functions and reasoning about programs.
1970-1980, David Turner developed a number of lazy functional languages, culminating in the Miranda system.
1987, An international committee of researchers initiated the development of Haskell, a standard lazy functional language.
Haskell
Purely functional, general-purpose, strong static typing Language
Haskell began in 1987 when a committee of researchers got together to design a kick-ass language
2003, Haskell Report was published, that defined as stable version
Various versions - until 1990, Version 1.0 - 1.4- 1997, Haskell 98- 2006, Haskell prime- 2010, Haskell 2010
Some features - like Haskell can take infinite list,- Lazy evaluation, statically typed, lots of errors are caught on compile time- Pattern Matching- Function as first class citizen- immutability etc.
Current application of Haskell ABN AMRO Amsterdam, The Netherlands, For Investment Banking activities
Aetion Technologies LLC, Columbus, Ohio , artificial Intelligence
Alcatel-Lucent, have used Haskell to prototype narrowband software radio systems, running in (soft) real-time
AT&T, Haskell is being used in the Network Security division to automate processing of internet abuse complaints.
Bank of America Merril Lynch, Haskell is being used for backend data transformation and loading.
Facebook, Facebook uses some Haskell internally for tools. lex-pass is a tool for programmatically manipulating a PHP code base via Haskell.
More - https://www.haskell.org/haskellwiki/Haskell_in_industry
Web Frameworks, -Yesod, Happstack, Snap etc.
Getting started With HaskellWhat do we need for HASKELL..?
- A Text editor and a Compiler
- GHC, Haskell compiler
- GHCI, GHC Interactive mode
- GHC can be downloaded from https://haskell.org/
- GHC Can take .hs file , extension , and compile it.
- After installation to start -> Type ghci on terminal
Some mostly used GHCI Commands GHCI Lets several commands to interpret with the GHC Compiler.
The library file Prelude.hs provides a large number of standard functions. In addition to the familiar numeric functions such as + and *, the library also provides many useful functions on lists.
GHCI Commands always starts with “:”
Some of the important commands are
:l – it loads the .hs file eg. :l myhaskellFile.hs
:r – it reloads the Haskell file :r myhaskellFile.hs
:help, :? – help
:add - adds module
:quit – quits GHCI
: show modules – lists loaded modules
More - https://downloads.haskell.org/~ghc/7.6.3/docs/html/users_guide/ghci-commands.html
Simple expressions and functions
- what if you try –> 2 * -2, well that error, we should write as -> 2 * (-2)
Boolean Algebra and Equality operation
5 + “mystring" or 5 == true?
well it will throw error as type does not match.
Calling out some pre built functions Haskell provides some predefined functions like min, max, succ etc.
Defining custom Functions Lets create 1.hs and inside it write code as
cubeit x = x * x * x
And save as 1.hs, now on ghci load as -> :l 1 and call function as ->
cubeit 3
Some examples of writing functions
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
So lets modify the above code as
If statements in Haskell
if else if else
Case in Haskell
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
Function naming convention
Lists in Haskell
- homogenous data structure
- various operations can be don with lists like
- Accessing the element of list
A list can be a collection of list
Like arithmetic various operations can be performed with lists
Haskell also provides predefined functions for list like
- head [5,4,3,2,1] => 5
- tail [5,4,3,2,1] => [4,3,2,1]
- last [5,4,3,2,1] => 1- init [5,4,3,2,1] => [5,4,3,2]
some other are – reverse, length, null, maximum, minimum, sum etc.
Some mathematical Interpretation
Haskell interpretation of the equation
Tuples in Haskell
Looks similar to lists but there is difference. Haskell List can have
infinite elements or can have one element.
Tuples is used when we know how many elements we want to
include. Lists of numbers can contain list of number.
Haskell lists can contain any types of elements but type and number
of elements in tuples has to be know
Eg. (1, true, 3, 5)
Tuples can also contain a collection of tuples.
Similar to lists tuples functions can be applied to tuples as well like
fst(1,2,4) => 1snd(5,6) => 6
Type and Type classes Static type->expression known at compile time -> safer code
It has type inference, like if we write number we don’t have to tell it’s number
A type is a name for a collection of related values. For example, in Haskell the
basic type
For eg. Boolean can contain two values true, false
Applying function to one or more argument of wrong type causes type error. Eg.
If evaluating an expression e would produce a value of type t, then e has type t,
written
Every well formed expression has a type, which can be automatically
calculated at compile time using a process called type inference.
> 1 + False , Error
e :: t
Finding types in Haskell
Basic Types in Haskell
Bool - logical values
Char - single characters
Integer - arbitrary-precision integers
Float - floating-point numbers
String - strings of characters
Int - fixed-precision integers
:t command tells the type
-> :: is has type of
-> so ‘a’ :: Char => a has type of char
List type in Haskell
A list is sequence of values of the same type:
[False,True,False] :: [Bool]
[’a’,’b’,’c’,’d’] :: [Char]
The type of a list says nothing about its length:
=> The type of the elements is unrestricted. For example, we can have lists of lists:
[[’a’],[’b’,’c’]] :: [[Char]]
Tuple Types
A tuple is a sequence of values of different types:
(False,True) :: (Bool,Bool)
(False,’a’,True) :: (Bool,Char,Bool)
The type of a tuple encodes its size:
(False,True) :: (Bool,Bool)
(False,True,False) :: (Bool,Bool,Bool)
(’a’,(False,’b’)) :: (Char,(Bool,Char))
(True,[’a’,’b’]) :: (Bool,[Char])
The type of the components is unrestricted:
Basic Usage
=> Shows type of Int->Int->Int->int
=> Here, it is mapping of three integer inputs to one integer output
=> The first three Int tells that it takes 3 integer inputs and the last Int is an output
of integer type.
Type Variables
What if we enter => :t head
=> Well that [a] is not a type. Type always begin with Capital letter. So it’s type
variable that means it can be of any type.
User Defined types and Type class
We can define our own types in Haskell using a data declaration,
e.g. data bool = True | False
data color = Red | Green | Blue
Both Bool and Color are examples of enumerated types,
since they consist of a finite number of nullary data constructors.
=> a type class is a type system construct that supports ad hoc polymorphism(Kind of
polymorphism In which polymorphic function can be applied to arguments of
different type)
What if you type ..
ghci> :t (==)
(==) :: (Eq a) => a -> a -> Bool
==, +, *, -, / are functions,
Everything before the => symbol is called a class constraint. the equality
function takes any two values that are of the same type and returns a
Bool and type of two values must be a member of Eq class.
Some Basic Type classes
EQ => used for types that support equality. The functions its members implement are == and /=.
So if there's an Eq class constraint for a type variable in a function, it uses == or /= somewhere
inside its definition
Ord is for types that have an ordering. Covers comparing functions like > < = >= <= or
LT GT EQ
Basic Class types continued..
Show It takes a value whose type is a member of Show and presents it to us as a string
Read is sort of the opposite typeclass of Show. The read function takes a string and
returns a type which is a member of Read.
Enum members are sequentially ordered types — they can be enumerated. The main
advantage of the Enum typeclass is that we can use its types in list ranges. Types in this
class: (), Bool, Char, Ordering, Int, Integer, Float and Double
Bounded members have an upper and a lower bound.
Others are Num, integral and floating.
EndReferences
http://learnyouahaskell.com/
http://Haskell.org/