計算機科学のブログ

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

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

コード

lesson/app/Main.hs

module Main (main) where

import Lib
  (
  )

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

c :: Num a => a -> IO a
c = \x -> return $ b x

main :: IO ()
main = do
  n <- c 1 :: IO Int
  print n

入出力結果(Terminal, Zsh)

% stack exec lesson-exe
3
% stack ghci
Using main module: 1. Package `lesson' component lesson:exe:lesson-exe with main-is file: /Users/…/app/Main.hs
The following GHC options are incompatible with GHCi and have not been passed to it: -threaded
Configuring GHCi with the following packages: lesson

* * * * * * * *

Warning: Multiple files use the same module name:
         * Paths_lesson found at the following paths
           * /Users/…/.stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/autogen/Paths_lesson.hs (lesson:lib)
           * /Users/…/.stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/lesson-exe/autogen/Paths_lesson.hs (lesson:exe:lesson-exe)
* * * * * * * *

GHCi, version 9.0.2: 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
[1 of 3] Compiling Lib              ( /Users/…/src/Lib.hs, interpreted )
[2 of 3] Compiling Main             ( /Users/…/app/Main.hs, interpreted )
[3 of 3] Compiling Paths_lesson     ( /Users/…/.stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/autogen/Paths_lesson.hs, interpreted )
Ok, three modules loaded.
Loaded GHCi configuration from /private/var/folders/wj/52wjq8dn0fj1qltsnx3xxpnh0000gn/T/haskell-stack-ghci/a8446316/ghci-script
*Main Lib Paths_lesson
λ> :load Main 

<no location info>: warning: [-Wmissing-home-modules]
    Modules are not listed in command line but needed for compilation: 
        Lib
[1 of 2] Compiling Lib              ( /Users/…/src/Lib.hs, interpreted )
[2 of 2] Compiling Main             ( /Users/…/app/Main.hs, interpreted )
Ok, two modules loaded.
(0.01 secs,)
*Main
λ> :t c
c :: Num a => a -> IO a
*Main
λ> :q
Leaving GHCi.
%