A while ago I wrote a program in Java doing some filtering and displaying without using for while statements and another one using lambdaj java library.
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.
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]
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))
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:
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.
Enregistrer un commentaire