計算機科学のブログ

コンテキストでの型の操作 Monad型クラス return、ラムダ、IO

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON 30(Monad型クラス)、30.3(Monad型クラス)のクイックチェック 30-4の解答を求めてみる。

コード

x :: Num a => a -> a
x = (+ 2)

y :: Num a => a -> IO a
y =  \n -> return ((+ 2) n)

入出力結果(Terminal, Zsh)

% ghci
GHCi, version 8.10.6: https://www.haskell.org/ghc/  :? for help
macro 'doc' overwrites builtin command.  Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /Users/.../.ghc/ghci.conf
Prelude
λ> :load sample04.hs 
[1 of 1] Compiling Main             ( sample04.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> :t x
x :: Num a => a -> a
*Main
λ> :t y
y :: Num a => a -> IO a
*Main
λ> z = y 10
z :: Num a => IO a
(0.00 secs, 60,800 bytes)
*Main
λ> z
12
it :: Integer
(0.01 secs, 61,368 bytes)
*Main
λ> w <- z
w :: Integer
(0.00 secs, 58,728 bytes)
*Main
λ> w
12
it :: Integer
(0.00 secs, 61,072 bytes)
*Main
λ> :t z
z :: Num a => IO a
*Main
λ> :t w
w :: Integer
*Main
λ> :quit
Leaving GHCi.
%