wvogel日記

自分用の技術備忘録が多めです.

IORef

ページビューが、今ちょうど66666!!

状態保存(変数保存)の方法が、Stateモナド以外にあると聞いて。
IORefで行えるようです。
いろんなサイトみてたらちょくちょく見かけたので、
どのようなものか、触ってみた

import Data.IORef

main = do n <- newIORef 0
          checkStr "haskell" 0 n
          count <- readIORef n
          print count

--checkStr :: String -> Int -> IORef Int -> IO()
checkStr str n ref 
 | length str == n = print "success"
 | otherwise = do
  (c:_) <- getLine
  modifyIORef ref (+1)
  if c == head (drop n str)
    then print (drop (n+1) str) >> checkStr str (n+1) ref
    else print (drop n str) >> checkStr str n ref

Stateモナドとやっていることは同じ??
ただ、Stateモナドと違ってコード内に明示しないといけないようです。