Skip to content

Commit 905410c

Browse files
Replace pattern matching with if/then/else in Chapter 4 examples. (#272)
* Replace pattern matching in examples with if/then/else. Pattern matching has not yet been introduced at this stage in the book. * Update text/chapter4.md Co-authored-by: milesfrain <[email protected]> Co-authored-by: milesfrain <[email protected]>
1 parent ad956d9 commit 905410c

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

text/chapter4.md

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,11 @@ Here is the usual _factorial function_ example:
3232

3333
```haskell
3434
fact :: Int -> Int
35-
fact 0 = 1
36-
fact n = n * fact (n - 1)
35+
fact n =
36+
if n == 0 then
37+
1
38+
else
39+
n * fact (n - 1)
3740
```
3841

3942
Here, we can see how the factorial function is computed by reducing the problem to a subproblem - that of computing the factorial of a smaller integer. When we reach zero, the answer is immediate.
@@ -42,13 +45,17 @@ Here is another common example, which computes the _Fibonacci function_:
4245

4346
```haskell
4447
fib :: Int -> Int
45-
fib 0 = 1
46-
fib 1 = 1
47-
fib n = fib (n - 1) + fib (n - 2)
48+
fib n =
49+
if n == 0 || n == 1 then
50+
1
51+
else
52+
fib (n - 1) + fib (n - 2)
4853
```
4954

5055
Again, this problem is solved by considering the solutions to subproblems. In this case, there are two subproblems, corresponding to the expressions `fib (n - 1)` and `fib (n - 2)`. When these two subproblems are solved, we assemble the result by adding the partial results.
5156

57+
Note that, while the above examples of `fact` and `fib` work as intended, a more idiomatic implementation would use pattern matching instead of `if`/`then`/`else`. Pattern matching techniques are discussed in a later chapter.
58+
5259
## Recursion on Arrays
5360

5461
We are not limited to defining recursive functions over the `Int` type! We will see recursive functions defined over a wide array of data types when we cover _pattern matching_ later in the book, but for now, we will restrict ourselves to numbers and arrays.

0 commit comments

Comments
 (0)