Advertisement
Guest User

Untitled

a guest
Apr 26th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Type annotation (optional, same for each implementation)
  2. factorial :: (Integral a) => a -> a
  3.  
  4. -- Using recursion (with the "ifthenelse" expression)
  5. factorial n = if n < 2
  6.               then 1
  7.               else n * factorial (n - 1)
  8.  
  9. -- Using recursion (with pattern matching)
  10. factorial 0 = 1
  11. factorial n = n * factorial (n - 1)
  12.  
  13. -- Using recursion (with guards)
  14. factorial n
  15.    | n < 2     = 1
  16.    | otherwise = n * factorial (n - 1)
  17.  
  18. -- Using a list and the "product" function
  19. factorial n = product [1..n]
  20.  
  21. -- Using fold (implements "product")
  22. factorial n = foldl (*) 1 [1..n]
  23.  
  24. -- Point-free style
  25. factorial = foldr (*) 1 . enumFromTo 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement