comparison 7-Haskell/factorial.hs @ 87:2b5341fc4555

Add Haskell Day 1 code and notes
author IBBoard <dev@ibboard.co.uk>
date Sat, 15 Jun 2019 17:31:22 +0100
parents
children
comparison
equal deleted inserted replaced
86:ab08b4bcd4a9 87:2b5341fc4555
1 module Factorial where
2 -- The book says to use "Main", but that now triggers "The IO action ‘main’ is not defined in module ‘Main’". https://optimistictypes.com/compiler-errors/#module-main-where says Main is special and must have a function "main".
3 -- Instead we'll use our own module name, because it doesn't seem to be important (yet).
4
5 -- Without pattern matching
6 fact :: Integer -> Integer
7 -- Note how this is like a Python "x if a else y"
8 fact x = if x == 0 then 1 else x * fact (x - 1)
9
10 -- With pattern matching
11 factorial :: Integer -> Integer
12 factorial 0 = 1
13 factorial x = x * factorial(x - 1)
14
15 -- With guards
16 factorial_guard :: Integer -> Integer
17 factorial_guard x
18 -- List of definitions, which look similar to the pattern matching but without the function name
19 | x > 1 = x * factorial(x - 1)
20 -- And the fallback "otherwise" result
21 | otherwise = 1