Skip to content

Instantly share code, notes, and snippets.

@jakab922
Created March 25, 2016 14:55
Show Gist options
  • Save jakab922/f6e4deceeb1b7fb06b14 to your computer and use it in GitHub Desktop.
Save jakab922/f6e4deceeb1b7fb06b14 to your computer and use it in GitHub Desktop.
{-
The file is based on:
https://ocharles.org.uk/blog/guest-posts/2014-12-07-list-comprehensions.html
-}
{-# LANGUAGE TransformListComp, RecordWildCards #-}
import GHC.Exts (groupWith, the)
import Data.Ord (comparing)
import Data.List (sortBy)
{-
The group syntax is
then group by <proj_func> [using <group_func>]
"group_func" is via which the grouping is made. It has a type signature of "Ord b => (a -> b) -> [a] -> [[a]]. "proj_func" is the first argument of "group_func" and this is the part of the input structure via which the grouping is made.
-}
data Character = Character {
first_name :: String,
last_name :: String,
birth_year :: Int
} deriving (Show, Eq)
friends :: [Character]
friends = [
Character "Bubba" "Johnes" 1975,
Character "Daniel" "Papp" 1983,
Character "Uh" "Oh" 1983,
Character "Joe" "Smith" 1975,
Character "Osama" "Bin Laden" 1955]
-- Sorts based on the total length of strings in the group
groupFunc f = sortBy (comparing (length . concatMap last_name)) . groupWith f
stuff :: [Character] -> [(Int, [String])]
stuff tbl = [(the birth_year, last_name) -- Just notice the "the" function in front of birth_year
| Character{..} <- tbl,
then group by birth_year using groupFunc
]
main = print $ stuff friends
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment