1
0

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.

【解答例】Haskell IOモナド 超入門

Last updated at Posted at 2014-12-11

Haskell IOモナド 超入門の解答例です。

シャッフル

【問1】次のコードからdoを取り除いて、bindやreturnは使わずにunIOIOで書き換えてください。

{-# LANGUAGE UnboxedTuples #-}

import GHC.Base
import System.Random

shuffle [] = IO $ \s -> (# s, [] #)
shuffle xs = IO $ \s ->
    let (# s1, n   #) = unIO (getStdRandom $ randomR (0, length xs - 1) :: IO Int) s
        (# s2, xs' #) = unIO (shuffle $ take n xs ++ drop (n + 1) xs) s1
    in  (# s2, (xs !! n) : xs' #)

main = IO $ \s ->
    let (# s1, xs #) = unIO (shuffle [1..9]) s
        (# s2, r  #) = unIO (print xs) s1
    in  (# s2, r  #)
実行結果(毎回異なる)
[3,5,4,9,2,7,8,6,1]

再実装

【問2】IOモナドを扱うbindreturn'を実装してください。>>=, <<=, <-, returnは使わないでください。

{-# LANGUAGE UnboxedTuples #-}

import GHC.Base

a `bind` b = IO $ \s ->
    let (# s1, r1 #) = unIO a s
        (# s2, r2 #) = unIO (b r1) s1
    in  (# s2, r2 #)

return' x = IO $ \s -> (# s, x #)

main = return' "hello" `bind` putStr `bind` print
実行結果
hello()
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?