Last active
August 29, 2015 14:24
-
-
Save nobsun/9a4a3698bb51c01d0c7b to your computer and use it in GitHub Desktop.
ランレングス変換 ref: http://qiita.com/nobsun/items/5518acd626e81c5944fb
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
import Control.Applicative ((<*>)) | |
import Control.Arrow (first,(***)) | |
runlength :: (Eq a) => [a] -> [(a,Int)] | |
runlength = hylo ((:) . runlen) [] null (span' . (==) . head <*> id) | |
runlen :: ([a],Int) -> (a,Int) | |
runlen = first head | |
hylo f e p g x = if p x then e else f y (hylo f e p g x') | |
where (y,x') = g x | |
span' :: (a -> Bool) -> [a] -> (([a],Int),[a]) | |
span' p xxs = case xxs of | |
x:xs | p x -> first (cons x) (span' p xs) | |
_ -> (([],0),xxs) | |
cons :: a -> ([a],Int) -> ([a],Int) | |
cons x = (x:) *** (1+) |
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
import Control.Arrow (first,(***)) | |
import Data.List (unfoldr) | |
runlength :: (Eq a) => [a] -> [(a,Int)] | |
runlength = map runlen . group' | |
runlen :: ([a],Int) -> (a,Int) | |
runlen = first head | |
group' :: Eq a => [a] -> [([a],Int)] | |
group' = unfoldr phi g | |
where | |
phi [] = Nothing | |
phi xxs@(x:_) = Just (span' (x==) xxs) | |
span' :: (a -> Bool) -> [a] -> (([a],Int),[a]) | |
span' p xxs = case xxs of | |
x:xs | p x -> first (cons x) (span' p xs) | |
_ -> (([],0),xxs) | |
cons :: a -> ([a],Int) -> ([a],Int) | |
cons x = (x:) *** (1+) |
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
import Control.Applicative ((<*>)) | |
import Data.List (group) | |
runlength :: (Eq a) => [a] -> [(a,Int)] | |
runlength = map runlen . group | |
runlen :: [a] -> (a,Int) | |
runlen = (,) . head <*> length |
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
import Data.List (unfoldr) | |
runlength :: (Eq a) => [a] -> [(a,Int)] | |
runlength = unfoldr phi | |
where | |
phi [] = Nothing | |
phi xxs@(x:_) = Just (runlen (x,0) xxs) | |
runlen :: (Eq a) => (a,Int) -> [a] -> ((a,Int),[a]) | |
runlen xn@(x,n) yys@(y:ys) | x == y = runlen (x,1+n) ys | |
| otherwise = (xn,yys) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment