diff 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
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/7-Haskell/factorial.hs	Sat Jun 15 17:31:22 2019 +0100
@@ -0,0 +1,21 @@
+module Factorial where
+    -- 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".
+    -- Instead we'll use our own module name, because it doesn't seem to be important (yet).
+
+    -- Without pattern matching
+    fact :: Integer -> Integer
+    -- Note how this is like a Python "x if a else y"
+    fact x = if x == 0 then 1 else x * fact (x - 1)
+
+    -- With pattern matching
+    factorial :: Integer -> Integer
+    factorial 0 = 1
+    factorial x = x * factorial(x - 1)
+
+    -- With guards
+    factorial_guard :: Integer -> Integer
+    factorial_guard x
+        -- List of definitions, which look similar to the pattern matching but without the function name
+        | x > 1 = x * factorial(x - 1)
+        -- And the fallback "otherwise" result
+        | otherwise = 1
\ No newline at end of file