Download haskell - Piazza

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Mathematical optimization wikipedia , lookup

Transcript
HASKELL
Installation and exercises
Installation
• http://www.haskell.org
• Main Page  Download Haskell
• Haskell Engine + GHCi
– In Windows: Also WinGHCi
• GHCi: Haskell Compiler/Interpreter
GHCi
Interpreter: Try it out!
• Math Operations and Functions
– 2+2
– 10^2
– log(10)
• Lists
–
–
–
–
[1, 2, 3]
[1..10]
[“x”, ”y”, ”z”]
[‘x’, ’y’, ’z’]
• Variable Assignment
– let x = 5 in x^2 + 2*x + 4
Running Haskell Script Files
• Create a new file, “HelloWorld.hs”
– main = do putStrLn "Hello, world!"
• Change the current directory:
– :cd <Directory of HS file>
• Load the file:
– :load HelloWorld.hs
• Run the file:
– main
Running Haskell Files
Basic List Manipulation
•
•
•
•
•
•
•
•
•
•
Get first element: head <list>
Get last element: tail <list>
Get nth element: <list> !! N
Get first n elements: take n <list>
Remove first n elements: drop n <list>
Length of list: length <list>
Sum of numbers: sum <list>
Product of numbers: product <list>
Append lists: <list1> ++ <list2>
Reverse list: reverse <list>
Functions in Haskell
• Prefix Operations: Operation before operands.
– In Math: f(x,y) + z
– In Haskell: f x y + z
• Function has higher priority
– In Math: f(x,y+z)
– In Haskell: f x (y+z)
• Function of functions
– In Math: f(x,g(y))
– In Haskell: f x (g y)
• Recursion is highly encouraged
Defining functions
• Defined in a Haskell script file
– The “=“ operator
– Arguments
• Example:
– double x = x + x
– squared x = x * x
– hypothenuse x y = sqrt(x^2 + y^2)
Implicit Grouping
• Used when defining functions
• Same spacing/tabbing to denote groups
hypothenuse2 x y = sqrt(z)
where
z = x2 + y2
x2 = x^2
y2 = y^2
Exercises
• Fix the syntax error and try the following
program:
N = a ’div’ length xs
where
a = 10
xs = [1,2,3,4,5]
Exercises
• Write two possible definitions of the ‘lastOne’
function that selects the last element of a list.
• Write two possible definitions of an ‘init’
function that removes the last element of a
list.
• Write a function that receives a list and
returns a list of the original values of the list
plus two
Exercises
• Write a function for the factorial operation
• Write a function that receives a numerical
user input and returns the factorial of that
number
– To obtain user input:
• X <- readLn
• Write a function that receives a numerical
user input ‘x’ and returns a list from 0 to x
Exercises
• EXTRA: Write a function that calculates the
nth number of the Fibonacci sequence
– Fibonacci numbers:
• f(n) = f(n-1) + f(n-2)
• f(0) = 1
• f(1) = 1