Skip to content

Instantly share code, notes, and snippets.

@disolovyov
Created May 23, 2012 19:13
Show Gist options
  • Select an option

  • Save disolovyov/2777177 to your computer and use it in GitHub Desktop.

Select an option

Save disolovyov/2777177 to your computer and use it in GitHub Desktop.
FP: Recursion - Homework

Recursion

Getting recursion involves trying recusion. Make your own implementations of standard Haskell functions you've seen and used before, namely: minimum, reverse, sum, product, take, drop, repeat, and cycle.

You can add an apostrophe suffix to the names of your versions of these functions to avoid naming conflicts. E.g. take becomes take'.

Try to implement as many as possible.

Examples of Recursive Solutions

-- Fibonacci numbers
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)

-- Maximum value in a list
maximum' [] = error "empty list"
maximum' [x] = x
maximum' (x:xs) =
    if x > maxInTail then x else maxInTail
  where
    maxInTail = maximum' xs


-- Make a list of n items with value x
replicate' n x
    | n <= 0    = []
    | otherwise = x : replicate' (n - 1) x

Bonus: FizzBuzz Again

Below is the FizzBuzz implementation created during the last session.

-- FizzBuzz
[
    if x `mod` 15 == 0 then "FizzBuzz"
    else if x `mod` 5 == 0 then "Fizz"
    else if x `mod` 3 == 0 then "Buzz"
    else show x
|
    x <- [1..50]
]

How can this be rewritten using guard syntax along with the list comprehension? Hint: don't try to squeeze all of it in one function.

Further Reading

To work towards understanding recursive function declarations, you can explore the following LYaH chapters:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment