Haskell Study Note Lesson 6 : Recursion

There are two types of recursion :

  1. Nested Recursion
  2. Pattern Matching

A typical recursion is like :

1
2
3
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)

The end of a recursion is called Base Case.

Practice :

Multiplication Table

1
2
3
4
5
6
7
8
9
10
11
multipleLine :: Int -> Int -> String
multipleLine n 0 = ""
multipleLine n i = multipleLine n (i - 1) ++ show(n) ++ "*" ++ show(i) ++ "=" ++ show(n * i) ++ " "

multipleRow :: Int -> String
multipleRow 0 = ""
multipleRow n = multipleRow (n - 1) ++ multipleLine n n ++ "\n"

main :: IO ()
main = do
putStr (multipleRow 9)

Note :

  1. Int is a value, but [Int] is a list
  2. If the parameter need operation, you should add ()
  3. The connect of strings is ++, and list is +