DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

Function of Getting Factors in Different Languages


Haskell

> factors n = [x | x <- [1..n], n `mod` x == 0]
> factors 4800 
...
> length $ factors 4800
42 

Add "let" before function definition when running in GHCi.

Python

>>> factors = lambda n: [x for x in range(1,n+1) if n % x == 0]
>>> factors(4800)
...
>>> len(factors(4800))
42

Clojure

user=> (defn factors [n] (filter #(= (mod n %) 0) (vec (range 1 (+ 1 n)))))
user=> (factors 4800) 
... 
user=> (count (factors 4800))
42

Ruby

> factors = lambda {|n| (1..n).to_a.collect {|x| x if n % x == 0}.compact} 
> factors.call(4800) 
=> ... 
> factors.call(4800).size
=> 42

Compare Ruby version with that of Python, Python's style is more "functional", while Ruby's style is pure object-oriented "object.message" format.



Published

Dec 17, 2013

Last Updated

Dec 17, 2013

Category

Tech

Tags

  • functional programming 9

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor