# Functional programming seminar (haskell)

Post on 18-Jul-2015

85 views

Embed Size (px)

TRANSCRIPT

<p>Functional Programming Seminar (Haskell)</p>
<p>Functional Programming Seminar (Haskell)- Bikram Thapa (245066)Todays Seminar ContentsA) Introduction To Functional Programming And Haskell, Features, ApplicationB) Getting Started With Haskell, Prerequisites C) Types And Type ClassesQuick Review of Functional ProgrammingProgramming 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 effectsRoots back from the lambda calculus since 1930Many functional programming languages based on lambda calculus principlesPurely 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 programmingA journal By John Hughes http://worrydream.com/refs/Hughes-WhyFunctionalProgrammingMatters.pdfBased on the original source of Chalmers memoFrom 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.</p>
<p>Javasum= 0;for (i = 1; i 10; ++i) sum= sum+i;Functional styleSum[1..10]Historical Background1930, 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.</p>
<p>HaskellPurely functional, general-purpose, strong static typing LanguageHaskell began in 1987 when a committee of researchers got together to design a kick-ass language2003, Haskell Report was published, that defined as stable versionVarious versions - until 1990, Version 1.0 - 1.4- 1997, Haskell 98- 2006, Haskell prime- 2010, Haskell 2010Some 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.</p>
<p>Current application of HaskellABN AMRO Amsterdam, The Netherlands, For Investment Banking activities Aetion Technologies LLC, Columbus, Ohio , artificial IntelligenceAlcatel-Lucent, have used Haskell to prototype narrowband software radio systems, running in (soft) real-timeAT&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_industryWeb Frameworks, - Yesod, Happstack, Snap etc.</p>
<p>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</p>
<p>Some mostly used GHCI CommandsGHCI 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 modulesMore - https://downloads.haskell.org/~ghc/7.6.3/docs/html/users_guide/ghci-commands.htmlSimple expressions and functions- what if you try > 2 * -2, well that error, we should write as -> 2 * (-2)</p>
<p>Boolean Algebra and Equality operation5 + mystring" or 5 == true?well it will throw error as type does not match.</p>
<p>Calling out some pre built functionsHaskell provides some predefined functions like min, max, succ etc.</p>
<p>Defining custom FunctionsLets create 1.hs and inside it write code as cubeit x = x * x * xAnd save as 1.hs, now on ghci load as -> :l 1 and call function as -> cubeit 3</p>
<p>Some examples of writing functionsMathematicsHaskellf(x)f(x,y)f(g(x))f(x,g(y))f(x)g(y)f xf x yf (g x)f x (g y)f x * g ySo lets modify the above code as </p>
<p>If statements in Haskellif else if else</p>
<p>Case in Haskell</p>
<p>Function and argument names must begin with a lower-case letter. For example:myFunfun1arg_2xBy convention, list arguments usually have an s suffix on their name. For example:xsnsnssFunction naming conventionLists in Haskell</p>
<p>homogenous data structure</p>
<p>various operations can be don with lists like </p>
<p>Accessing the element of list </p>
<p>A list can be a collection of list</p>
<p>Like arithmetic various operations can be performed with lists </p>
<p>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]</p>
<p>some other are reverse, length, null, maximum, minimum, sum etc.</p>
<p>Some mathematical InterpretationHaskell interpretation of the equation</p>
<p>Tuples in HaskellLooks 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 likefst(1,2,4) => 1snd(5,6) => 6Type and Type classesStatic type->expression known at compile time -> safer codeIt has type inference, like if we write number we dont have to tell its number A type is a name for a collection of related values. For example, in Haskell the basic typeFor eg. Boolean can contain two values true, falseApplying function to one or more argument of wrong type causes type error. Eg.</p>
<p>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.</p>
<p>> 1 + False , Errore :: tFinding types in HaskellBasic Types in HaskellBool- logical valuesChar- single charactersInteger- arbitrary-precision integersFloat- floating-point numbersString- strings of charactersInt- fixed-precision integers:t command tells the type-> :: is has type of -> so a :: Char => a has type of char </p>
<p>List type in HaskellA list is sequence of values of the same type:</p>
<p>[False,True,False] :: [Bool][a,b,c,d] :: [Char]The type of a list says nothing about its length:</p>
<p>=> The type of the elements is unrestricted. For example, we can have lists of lists:</p>
<p>[[a],[b,c]] :: [[Char]]Tuple TypesA tuple is a sequence of values of different types:(False,True) :: (Bool,Bool)(False,a,True) :: (Bool,Char,Bool)26The 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.</p>
<p>Type VariablesWhat if we enter => :t head=> Well that [a] is not a type. Type always begin with Capital letter. So its type variable that means it can be of any type.</p>
<p>User Defined types and Type classWe can define our own types in Haskell using a data declaration,e.g. data bool = True | False data color = Red | Green | Blue</p>
<p> 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(==)(==)::(Eqa)=>a->a->Bool</p>
<p>==, +, *, -, / 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 classesEQ => 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</p>
<p>Ord is for types that have an ordering. Covers comparing functions like > < = >= </p>

Recommended

View more >