3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

IORefとState

Last updated at Posted at 2014-11-21

Haskellの実験メモです。

IORefからStateに話を繋げられないかと考えています。

IORefとStateで変数を書き換える動作を模倣してみました。

import Data.IORef
import Control.Monad.State

test1 n = do
    a <- newIORef n
    if n == 1
        then writeIORef a $ n + 10
        else writeIORef a $ n + 1
    modifyIORef a (+ 5)
    readIORef a

test2 = execState $ do
    n <- get
    if n == 1
        then put $ n + 10
        else put $ n + 1
    modify (+ 5)

main = do
    print =<< test1 1
    print  $  test2 1
実行結果
16
16

Stateは処理後に外せるのが便利だと思いました。

unsafePerformIOはナシです。

3
4
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?