Personal tools

Haskell Quiz/DayRange/Solution Jethr0

From HaskellWiki

< Haskell Quiz | DayRange(Difference between revisions)
Jump to: navigation, search
m
 
m (added example)
Line 2: Line 2:
   
 
<haskell>
 
<haskell>
  +
-- > dayRange [1,2,3,6,7]
  +
-- "Mon-Wed, Sat, Sun"
 
dayRange = sepComma . map range . map (map toWeekday) . groupAscend . sort
 
dayRange = sepComma . map range . map (map toWeekday) . groupAscend . sort
 
where sepComma = concat . intersperse ", "
 
where sepComma = concat . intersperse ", "

Revision as of 17:54, 16 December 2006


-- > dayRange [1,2,3,6,7]
-- "Mon-Wed, Sat, Sun"
dayRange = sepComma . map range . map (map toWeekday) . groupAscend . sort
    where sepComma    = concat . intersperse ", "
          toWeekday x = weekdays!!(x-1)
          range xs | length xs < 3 = sepComma xs
                   | otherwise     = head xs ++ "-" ++ last xs
          weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
 
groupAscend (x:xs) = together $ foldl ascend ([],[x]) xs
    where ascend (done,curr) e = if e == (last curr)+1 then (done,         curr++[e])
                                                       else (done++[curr], [e])
          together (a,b) = a++[b]