Kat Chuang
November 12, 2013
370

Presented by Ryan Trinkle
Slides by Kat Chuang

Kat Chuang

November 12, 2013

Transcript

November 12, 2013

● Expressive
● Declarative
● Strongly typed
● Easy to refactor
● Referentially transparent

3. Project Euler #1
Multiples of 3 and 5
sum [x | x <- [1..999] , x `mod` 3 == 0 || x `mod` 5 == 0]
C
int main(void)
{
int total=0;
int i=0;
while(i<1000)
{
if(i%3==0 || i%5==0)
total+=i;
i++;
}
printf("%d", total);
}
Python
def multiples_of_3_or_5():
for number in xrange(1000):
if not number % 3 or not number % 5:
yield number
print sum(multiples_of_3_or_5())
Or, you can use list comprehension
print sum( number for number in xrange(1000) if not (number % 3 and number % 5) )

"Hello, world!" :: String
value type

5. Basic types
Text
● 'a' :: Char
● "asdf" :: String
Numbers
● 1 :: Integer
● 0.5 :: Double
Booleans
● True :: Bool
● False :: Bool
Functions
● square ::
Integer -> Integer

6. Containers
Lists
● [1, 2, 3] :: [Integer]
● ["Hello", "Goodbye"] :: [String]
● [True, False, True] :: [Bool]
Tuples
● (1, 2) :: (Integer, Integer)
● (1, "Hello", True) :: (Integer, String, Bool)

7. Containers
Tuples of lists and vice versa
● [(1, "Hello"), (2, "Goodbye")] ::
[(Integer, String)]
● ([1, 2, 3], ["Hello", "Goodbye"]) ::
([Integer], [String])

8. GHCi Exercise - Type these commands
Prelude> :t 'a'
'a' :: Char
Prelude> :t "Hello"
"Hello" :: [Char]
Why is it [Char], not String?
type String = [Char]

9. GHCi Exercise - Type these commands
Prelude> :t 1
1 :: Num a => a
Prelude> :t 0.5
0.5 :: Fractional a => a
Why? 1 can be used with any numeric type;
0.5 can be used with any numeric type that
supports fractions

1 :: Num a => a
"1 can have any type a, where a is a numeric type"
The context comes before the =>, and tells us about the
type that follows.
value type
context

1 :: Num a => a
Num is a typeclass, not a type. A typeclass tells you about a
type.
Num a tells you that the type a must support numeric
operations like +, *, and -
value type
context

12. Functions
Prelude> let square x = x^2
Prelude> square 5
25
Prelude> :t square
square :: Num a => a -> a

square :: Num a => a -> a
"square is a function that takes an a and returns an a,
where a is a numeric type."
Note: the input and output type must match: square
cannot return a Float if you give it an Int.
value
input output
context type

14. GHCi
Prelude> :i Num
You can use :i to get
something in GHCi.
For a typeclass, :i will give
you its operations and a list
of types that are its
instances.
class Num a where
(+) :: a -> a -> a
(*) :: a -> a -> a
(-) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
fromInteger :: Integer -> a
-- Defined in `GHC.Num'
instance Num Integer -- Defined in `GHC.Num'
instance Num Int -- Defined in `GHC.Num'
instance Num Float -- Defined in `GHC.Float'
instance Num Double -- Defined in `GHC.Float'

15. Books