dimanche, avril 04, 2010

Java vs Haskell


At that time I did not know it, but I was doing some kind of functional programming. I discovered Haskell a few weeks ago, and I duplicated what I did in Java.

As you can guess the Haskell code is way shorter, and goes even a little further.

1 Have a list of people belonging to various countries:
European people: [Eric from France, Martine from France, John from Great-Britain, Martha from Great-Britain, Carine from France, Gerd from Deutschland, Giuseppe from Italia, Martha from Deutschland]

2 Get the different countries:

European countries: ["Deutschland","France","Great-Britain","Italia"]

3 List the people that belong to each country
:
People from: [France]: [Carine from France, Eric from France, Martine from France]
People from: [Deutschland]: [Gerd from Deutschland, Martha from Deutschland]
People from: [Great-Britain]: [John from Great-Britain, Martha from Great-Britain]
People from: [Italia]: [Giuseppe from Italia]

Here is the code:
import Data.List
import Data.Function

le = [
("Eric", "France"),("Martine", "France"),
("John", "Great-Britain"),("Martha", "Great-Britain"),("Carine", "France"),
("Gerd", "Deutschland"),("Giuseppe", "Italia"),("Martha", "Deutschland")
]

dla xs = "European people: " ++ show [ fst x ++ " from " ++ snd x | x <- xs]
lc xs = [ head y | y <- group(sort([ snd x | x <- xs]))]
dlc = "European countries: " ++ show(lc le)

lpc5 xps = groupBy (\x y -> snd x == snd y) (sortBy (compare `on` snd)([ xp | xp <-xps ]))
lpc9 xps = unlines [ "People from " ++ show (snd (head xp)) ++ ":" ++ (show [fst x | x<-xp ]) | xp <-xps ]
fait9 = do { m <- [lpc5 le]; lpc9 m }
dlad = [ dla le, dlc, fait9 ]

main = putStrLn (unlines(dlad))

1 commentaire:

Luiz a dit…

Great algorithm, but I think the code could be improved with better variable names. That way, the Haskell version of your problem would be even more impressive.