Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 0.96 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. {-
  2. λ> toRList [13,81,80,79,78,77,76,19,40,41,42,43,44,45,48]
  3. Cons 13 (Sequence 81 76 (Cons 19 (Sequence 40 45 (Cons 48 Nil))))
  4. λ> fromRList (Cons 13 (Sequence 81 76 (Cons 19 (Sequence 40 45 (Cons 48 Nil)))))
  5. [13,81,80,79,78,77,76,19,40,41,42,43,44,45,48]
  6. -}
  7.  
  8. data RList = Cons Int RList
  9.            | Sequence Int Int RList
  10.            | Nil
  11.            deriving (Show, Eq, Ord)
  12.  
  13. toRList :: [Int] -> RList
  14. toRList = foldr f Nil
  15.   where
  16.     f :: Int -> RList -> RList
  17.     f x list = case list of
  18.         Nil -> Cons x Nil
  19.         Cons y l ->
  20.             if x `elem` [y-1, y+1] then Sequence x y l
  21.             else Cons x list
  22.         Sequence f t l ->
  23.             if (x == f+1 && f > t) || (x == f-1 && f < t) then Sequence x t l
  24.             else Cons x list
  25.  
  26. fromRList :: RList -> [Int]
  27. fromRList list = case list of
  28.     Nil -> []
  29.     Cons x l -> x : fromRList l
  30.     Sequence f t l ->
  31.         (if f > t then reverse [t..f] else [f..t]) ++ fromRList l