タブと半角空白文字を変換する
[*** Text版]
インポート
code: (haskell)
import Data.Bool
import Data.List
import Data.Text (Text)
import qualified Data.Text as T
[** TABをSPCに展開(untabify)]
定義例
code: (haskell)
untabify :: Text -> Text
untabify = T.unfoldr phi . (,) 1
where
phi (i,tx) = case T.uncons tx of
Nothing -> Nothing
Just ('\t', tx') -> bool (Just (' ',(succ i,tx)))
(Just (' ',(succ i, tx')))
(0 == mod i 8)
Just (c, tx') -> Just (c, (succ i, tx'))
[** SPCをTABへ畳み込み(tabify)]
定義例
code: (haskell)
tabify :: Text -> Text
tabify = T.concat . unfoldr phi . (,) 0 . untabify
where
phi (i, tx) = case T.uncons tx of
Nothing -> Nothing
Just (' ',_) -> case T.span (' ' ==) tx of
(sx,ux) -> bool (Just (sx, (i+j, ux)))
(Just (T.replicate (q'-q) "\t" T.append T.replicate r' " ",(i+j, ux)))
(q < q')
where
(q,r) = i divMod 8
(q',r') = (i+j) divMod 8
j = T.length sx
Just (c,tx') -> Just (T.singleton c, (succ i, tx'))
評価例
code:_
:set -XOverloadedStrings
sample = "abcdefg\t CDE\t"
sample
"abcdefg\t CDE\t"
untabify sample
"abcdefg CDE "
tabify (untabify sample)
"abcdefg\t CDE\t"
[*** String版]
インポート
code: (haskell)
import Data.Bool
import Data.List
[** TABをSPCに展開(untabify)]
定義例
code: (haskell)
untabify' :: String -> String
untabify' = unfoldr phi . (,) 1
where
phi (i,cs) = case uncons cs of
Nothing -> Nothing
Just ('\t', cs') -> bool (Just (' ',(succ i,cs)))
(Just (' ',(succ i, cs')))
(0 == mod i 8)
Just (c, tx') -> Just (c, (succ i, tx'))
[** SPCをTABへ畳み込み(tabify)]
定義例
code: (haskell)
tabify' :: String -> String
tabify' = concat . unfoldr phi . (,) 0 . untabify'
where
phi (i,cs) = case uncons cs of
Nothing -> Nothing
Just (' ',_) -> case span (' ' ==) cs of
(bs,ds) -> bool (Just (bs, (i+j, ds)))
(Just (replicate (q'-q) '\t' ++ replicate r' ' ', (i+j, ds)))
(q < q')
where
(q,r) = i divMod 8
(q',r') = (i+j) divMod 8
j = length bs
Just (c,cs') -> Just (c, (succ i, cs')) 評価例
code:_
sample = "abcdefg\t CDE\t"
sample
"abcdefg\t CDE\t"
untabify' sample
"abcdefg CDE "
tabify' (untabify' sample)
"abcdefg\t CDE\t"