計算機科学のブログ

HaskellのI/O バイナリデータの操作 グリッチング、バイトセクション、順序、System.Randomモジュール

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT4(HaskellのI/O)、LESSON25(バイナリデータの操作)、25.5(練習問題)Q25-2の解答を求めてみる。

コード

import Control.Monad (foldM)
import qualified Data.ByteString as BC
import System.Environment (getArgs)
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 fname = head args
  let n = read $ args !! 1
  imageFile <- BC.readFile fname
  glitched <-
    foldM
      (\b f -> f b)
      imageFile
      $ replicate n randomReverseBytes
  let glitchedFileName = mconcat ["glitched_", fname]
  BC.writeFile glitchedFileName glitched
  print "all done"

入出力結果(Terminal, Zsh)

% runghc sample2.hs lovecraft.jpg 1 && open glitched_lovecraft.jpg
"all done"
% runghc sample2.hs lovecraft.jpg 1 && open glitched_lovecraft.jpg
"all done"
% runghc sample2.hs lovecraft.jpg 1 && open glitched_lovecraft.jpg
"all done"
% runghc sample2.hs lovecraft.jpg 1 && open glitched_lovecraft.jpg
"all done"
% runghc sample2.hs lovecraft.jpg 1 && open glitched_lovecraft.jpg
"all done"
%