3 ms·
Asking as a complete newbie in this paradigm, but what's the benefit of writing factorial like this? fn factorial = | 0 => 1 \ y ~ x + 1 =
by erezsh 4y ago
Asking as a complete newbie in this paradigm, but what's the benefit of writing factorial like this?
fn factorial =
| 0 => 1
\ y ~ x + 1 => y * factorial(x)
Instead of
| y => y * factorial(y-1)?
- zesterer 4y agoSubtraction of natural numbers is non-total, and can result in negative numbers, which cannot be represented as a natural number. Most languages throw an exception, panic, etc. None of these are solutions I'm happy with. In Tao, natural numbers don't support subtraction but you can decrement them by pattern-matching as in this example, allowing the compiler to 'check your workings' and statically prove that your program can never result in underflows. In a similar vein, you can't index directly into a list (because indexing is a fallible operation). Instead, you must pattern-match on the list and explicitly handle the empty case (you can also write a utility function to do this for you like so) fn nth : Nat -> [A] -> Maybe A = | _, [] => None | 0, [x ..] => Just x \ n + 1, [.. tail] => tail->nth(n) Used like: [1, 2, 3]->nth(1) # Evaluates to `Some 2`