Skip to content

Instantly share code, notes, and snippets.

@JosephKiranBabu
Last active February 11, 2017 04:09
Show Gist options
  • Save JosephKiranBabu/d3bb67a7ec831321531ba5f3b8b4301b to your computer and use it in GitHub Desktop.
Save JosephKiranBabu/d3bb67a7ec831321531ba5f3b8b4301b to your computer and use it in GitHub Desktop.
Comparing sorting a list of employees by their salary in 4 languages.
Clojure
(def emps (map (fn [x] {:name (str "employee" x) :salary (* 100 x)}) (take 10 (range 1 10))))
(take (/ (count emps) 10) (reverse (sort-by :salary emps)))
Haskell
import Data.List (sortBy)
data Employee = Employee {name :: String, salary :: Double } deriving (Show)
let emps = map (\x -> Employee ("emp" ++ show x) (x * x)) [1..10] in take ((length emps) `div` 10) (sortBy (\x y -> compare (salary y) (salary x)) emps)
Scala
case class Employee(name: String, salary: Double)
val emps = (1 to 10).map(i => Employee("employee" + i, i * 100))
emps.sortBy(_.salary).reverse.take(math.ceil(emps.size / 10.0))
Python
emps = {"employee"+str(i): i*100 for i in range(1, 11)}
[(key, value) for key, value in sorted(emps.items(), key=lambda (k,v): (-v,k))][0:len(emps)/10]
@JosephKiranBabu
Copy link
Author

Must make the comparison uniform. Either use classes in all the languages or use maps instead.
If maps are used, it should be a 2-liner in any of the 4 languages - one line to generate the employees and another to sort them.

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