2006年03月18日
C++のコメントを抜き出す by Haskell
C++ のソースからコメントだけを抜き出したい衝動に駆られたのでおもむろに Haskell で実装.やはり簡単なプログラムの実装は Haskell のほうが簡単だ…
-- Extract C++ comments from stdin
import List
import System
-- for C-style comments, i.e. /* comments... */
judgeC (t,c) (c1,c2,c3)
= if t==0 && c2=='/' && c3=='*' then (1,0)
else if t==1 && c1=='*' && c2=='/' && c > 2 then (0,0)
else (t,c+1)
-- for C++-style comments, i.e. /* comments... */ or // comment... \n
judgeCXX (t,c) (c1,c2,c3)
= if t==0 && c2=='/' && c3=='/' then (2,0)
else if t==2 && c2=='\n' then (0,0)
else judgeC (t,c) (c1,c2,c3)
unfilterComments x judge =
let dx = (zip3 (" "++init x) x (tail x++" "))
cms = scanl judge (0,0) dx
cms' = zipWith (\(c1,_) (c2,_) -> c1 > 0 || c2 > 0) cms (tail cms)
in map (\(x,c) -> x) (filter (\(_,c) -> c) (zip x cms'))
main = getArgs >>=
(\args -> getContents >>=
(\x -> putStr (unfilterComments x
(if not (args ==[]) && head args == "-c"
then judgeC else judgeCXX))))
- Comments: 0
- TrackBack (Close): -