3 ms·
Beginner Haskell Solution: pascal 1 = [1] pascal 2 = [1,1] pascal n = [1] ++ sum' (pascal (n - 1)) sum' [] = [] sum' [1] = [1] sum' (x:xs) = [x + head' xs
by harichinnan 15y ago
Beginner Haskell Solution:
pascal 1 = [1]
pascal 2 = [1,1]
pascal n = [1] ++ sum' (pascal (n - 1))
sum' [] = []
sum' [1] = [1]
sum' (x:xs) = [x + head' xs] ++ sum' xs
head' [] = 0
head' xs = head xs
- nandemo 15y ago1) When you're writing a function on integers or lists using explicit recursion, usually there's need for only one base case. Do you really need a separate definition for pascal 2? What about sum' [1]? 2) Often it's better to use fold instead of explicit recursion. If you wonder whether you can rewrite your function in terms of fold... "A tutorial on the universality and expressiveness of fold" http://www.cs.nott.ac.uk/~gmh/fold.pdf http://www.cs.nott.ac.uk/~gmh/fold.pdf