— CPSC 312 – 2021 – Our First Haskell Program
module First where
— To run this program, do:
— ghci
— :load First
— Equality Provides definitions
x = y+3
y = 10
— Type declarations
— name :: type
con :: Integer
con = 7
con2 :: Double
con2 = 7
square :: Double -> Double — type declaration
square x = x*x
— Haskell Can Infer Types
fourth x = square (square x)
— Try:
— :type fourth
— Haskell can infer more general types
double x = x*2
— functions can have multiple arguments:
foo x y = 1000*x+y
— try:
— foo 9 3
— foo(9,3)
— (foo 9) 3
— :type foo
— :type (9,3)
— :type foo 9
— Functions can also be infix (if don’t start with letter or digit)
x %^&*$ y = 100000*x+y
–try
— 6 %^&*$ 7
— Infix functions can be made prefix by putting them in parentheses:
— (%^&*$) 6 7
— Prefix functions can be make infix by putting them between ` back-quotes
— 6 `foo` 7
— functions can be given some of their arguments…resulting in another function
foosev = foo 7
— Integers and Reals cannot be mixed!
— 100 / 7
— div 100 7
— div 100.0 7
— 100 `div` 7
— (/) 100 7
— :type div 100 7
— :type 1.5
— (div 100 7) + 1.5
— fromIntegral (div 100 7) + 1.5
— Looping arises from recursion:
— fac n returns n!
fac 0 = 1
fac n = n * fac (n-1)
— fib n returns the nth fibonacci number
fib :: Int -> Int
fib 0 = 1
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
— try:
— fib 30
— fib1 n returns the nth fibonacci number
fib1 0 = 1
fib1 n = fib2 (n-1) 1 1
— fib2 n f0 f1 where f0 and f1 are subsequent fibonacci number returns the
— nth fibonacci number after f1
fib2 0 f0 f1 = f1
fib2 n f0 f1 = fib2 (n-1) f1 (f0+f1)
–fib1 1000
–fib1 10000
— absol n returns the absolute value of n
absol n
| n >= 0 = n
| otherwise = -n
— length [3,5,2,9]
— :type length
— product [3,5,2,9]
— :type product
factorial n = product [1..n]
average ns = sum ns `div` length ns
— let myave ns = sum ns / length ns
— myave ns = sum ns / fromIntegral (length ns)
plus1 x = x+1
plus x y= x+y
pls(x,y) = x+y
ff f x = f (f x)
— Try:
— ff plus1 5
— ff (plus 6) 1
— ff (+ 6) 1
— ff (* 10) 2
fourthnew = ff square
— Infix operators
x ++++ y = 1000*x+y
— 7 ++++ 3
— (++++) 7 3
— (7 ++++) 3
— ((++++) 7) 3
— (++++ 7) 3
— ff (++++ 7) 4
— ff (7 ++++) 4
— ff ((++++) 7) 4
— (* 7) `ff` 2
qsort [] = []
qsort (x:xs) = qsort smaller ++ [x] ++ qsort larger
where
smaller = [e | e <- xs, e <= x]
larger = [e | e <- xs, e > x]
— Try:
— qsort [5,4,8,1,9,4,7]