計算機科学のブログ

コンテキストでの型の操作 Monad型クラス ApplicativeとFunctorの制限 Monad型クラス Monadを使ってHello Nameプログラムを作成する return関数、ラムダ

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

コード

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

g :: Num a => a -> IO a
g = \n -> return $ f n

main :: IO ()
main = do
  a <- g 10
  print a

入出力結果(Terminal, Zsh)

% ghci
GHCi, version 8.10.7: https://www.haskell.org/ghc/  :? for help
Loaded package environment from /Users/…/.ghc/x86_64-darwin-8.10.7/environments/default
:loadmacro '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.02 secs,)
*Main
λ> :t f
f :: Num a => a -> a
*Main
λ> :t g
g :: Num a => a -> IO a
*Main
λ> f 10
12
it :: Num a => a
(0.06 secs, 63,560 bytes)
*Main
λ> g 10
12
it :: Integer
(0.00 secs, 61,544 bytes)
*Main
λ> a <- g 10
a :: Integer
(0.00 secs, 58,736 bytes)
*Main
λ> a
12
it :: Integer
(0.01 secs, 61,096 bytes)
*Main
λ> :quit 
Leaving GHCi.
% runghc sample04.hs 
12
%