Alex
Alex

Reputation: 667

haskell: factorial using high order function

I'm trying to recreate a factorial function, eg fac 1 = 1, fac 2 = 2, fac 3 = 6 by using high order functions but I'm not having much luck. My fold function keeps returning the empty list no matter what inputs I'm giving it. Can anyone help me out?

Here's what I have so far:

fold f a [] = []
fold f a (x:xs) = fold f (f a x) xs


fac n = fold (*) 1 [1..n]

Upvotes: 2

Views: 1456

Answers (4)

Aleph0
Aleph0

Reputation: 6084

What about this?

fac n=product [1..n]

Upvotes: 1

Sergio Izquierdo
Sergio Izquierdo

Reputation: 333

With a fold over a list you can achieve it:

fact n = foldl1 (*) [1..n]

Upvotes: 1

Barak
Barak

Reputation: 43

You generate all factorial values as list.

facts = scanl (*) 1 [1 ..]

After that getting one value is just accessing the list.

factN n = facts !! n + 1

λ> factN 6
720

Upvotes: 0

jwodder
jwodder

Reputation: 57610

fold returns the empty list because its base case returns the empty list, and the recursive step never does anything with the result of the recursion. Obviously, at least one of those things needs to change, and in this instance, that should be the base case:

fold f a [] = a

Alternatively, you could just use foldl itself instead of trying to reimplement it.

Upvotes: 2

Related Questions