Created
December 4, 2013 13:53
-
-
Save epost/7787727 to your computer and use it in GitHub Desktop.
A little working example of Haskell's 'comprehensive comprehensions' as supported by the TransformListComp extension.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE TransformListComp #-} | |
-- There are three new keywords: group, by, and using. | |
-- The functions sortWith and groupWith are not keywords; they are ordinary functions that are exported by GHC.Exts.) | |
import GHC.Exts (sortWith, groupWith) | |
--import Data.List (sort) | |
-- actual syntax: http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#generalised-list-comprehensions | |
-- | |
-- original paper: http://research.microsoft.com/en-us/um/people/simonpj/papers/list-comp/list-comp.pdf | |
-- | |
-- this extension can also do CUBE aggregation instead of just relational stuff! | |
type Name = String | |
type Dept = String | |
type Salary = Int | |
employees :: [(Name, Dept, Salary)] | |
employees = [ ("Simon", "MS", 80) | |
, ("Erik", "MS", 100) | |
, ("Phil", "Ed", 40) | |
, ("Gordon", "Ed", 45) | |
, ("Paul", "Yale", 60)] | |
foo3 = [ (dept, sum salary) | |
| (name, dept, salary) <- employees | |
, then group by dept using groupWith | |
, then sortWith by (sum salary) | |
, then take 5 ] | |
foo1 = | |
map (\(name, salary) -> name) | |
(sortWith (\(name, salary) -> salary) | |
[ (name, salary) | |
| (name, dept, salary) <- employees | |
, salary < 50 ]) | |
main = do | |
-- putStrLn $ show foo1 | |
-- putStrLn $ show foo2 | |
putStrLn $ show foo3 | |
-- putStrLn $ map show foo | |
-- this library function removes duplicates in a list | |
-- nub :: Eq a => [a] -> [a] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment