Project Euler #1
Multiples of 3 and 5
Haskell
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) )
Slide 4
Slide 4 text
Reading types
"Hello, world!" :: String
value type
GHCi Exercise - Type these commands
Prelude> :t 'a'
'a' :: Char
Prelude> :t "Hello"
"Hello" :: [Char]
Why is it [Char], not String?
type String = [Char]
Slide 9
Slide 9 text
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
Slide 10
Slide 10 text
Reading types
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
Slide 11
Slide 11 text
Reading types
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
Slide 12
Slide 12 text
Functions
Prelude> let square x = x^2
Prelude> square 5
25
Prelude> :t square
square :: Num a => a -> a
Slide 13
Slide 13 text
Reading types
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
Slide 14
Slide 14 text
GHCi
Prelude> :i Num
You can use :i to get
information about
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'