HaskellのI/O バイナリデータの操作 バイトセクション、逆順、Data.ByteString.Char8モジュール、reverse関数、乱数の生成、System.Randomモジュール、randomRIO関数
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT4(HaskellのI/O)、LESSON 25(バイナリデータの操作)、25.5(練習問題)Q25-2の解答を求めてみる。
コード
import System.Environment ( getArgs )
import qualified Data.ByteString.Char8 as BC
import System.Random ( randomRIO )
reverseSection :: Int -> Int -> BC.ByteString -> BC.ByteString
reverseSection start size bytes =
let (before, rest) = BC.splitAt start bytes
(target, after) = BC.splitAt size rest
changed = BC.reverse target
in mconcat [before, changed, after]
randomReverseBytes :: BC.ByteString -> IO BC.ByteString
randomReverseBytes bytes = do
let sectionSize = 25
let bytesLength = BC.length bytes
start <- randomRIO (0, bytesLength - sectionSize)
return (reverseSection start sectionSize bytes)
main :: IO ()
main = do
args <- getArgs
let filePath = head args
imageFile <- BC.readFile filePath
glitched <- randomReverseBytes imageFile
let glitchedFileName = mconcat ["glitched_", filePath]
BC.writeFile glitchedFileName glitched
print "all done!"
入出力結果(Terminal, Zsh)
% runghc sample2.hs lovecraft.jpg
"all done!"
% open glitched_lovecraft.jpg
% runghc sample2.hs lovecraft.jpg
"all done!"
% open glitched_lovecraft.jpg
% runghc sample2.hs lovecraft.jpg
"all done!"
% open glitched_lovecraft.jpg
% runghc sample2.hs lovecraft.jpg
"all done!"
% open glitched_lovecraft.jpg
% runghc sample2.hs lovecraft.jpg
"all done!"
% open glitched_lovecraft.jpg
%