計算機科学のブログ

コンテキストでの型の操作 Applicative型クラス:関数をコンテキスト内で使用する 2つの都市の距離を計算するコマンドラインアプリケーション Maybe型、Int型、加算

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON 28(Applicative型クラス:関数をコンテキスト内で使用する)、28.1(2つの都市の距離を計算するコマンドラインアプリケーション)、クイックチェック 28-1の解答を求めてみる。

lesson/package.yaml

name:                lesson
version:             0.1.0.0
github:              "githubuser/lesson"
license:             BSD3
author:              "Author name here"
maintainer:          "example@example.com"
copyright:           "2022 Author name here"

extra-source-files:
- README.md
- CHANGELOG.md

# Metadata used when publishing your package
# synopsis:            Short description of your package
# category:            Web

# To avoid duplicated efforts in documentation and dealing with the
# complications of embedding Haddock markup inside cabal files, it is
# common to point users to the README.md file.
description:         Please see the README on GitHub at <https://github.com/githubuser/lesson#readme>

dependencies:
- base >= 4.7 && < 5

library:
  source-dirs: src

executables:
  lesson-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - lesson

tests:
  lesson-test:
    main:                Spec.hs
    source-dirs:         test
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - lesson

コード

lesson/app/Main.hs

module Main where

import Lib
  ( addMaybe,
  )

main :: IO ()
main = do
  mapM_
    ( \(x, y) ->
        putStrLn $
          mconcat
            [ show x,
              " + ",
              show y,
              " = ",
              show $ addMaybe x y
            ]
    )
    [ (Just 2, Just 3),
      (Just 2, Nothing),
      (Nothing, Just 3),
      (Nothing, Nothing)
    ]

lesson/src/Lib.hs

module Lib
  ( addMaybe,
  )
where

addMaybe :: Maybe Int -> Maybe Int -> Maybe Int
addMaybe Nothing _ = Nothing
addMaybe _ Nothing = Nothing
addMaybe (Just m) (Just n) = Just $ m + n

入出力結果(Terminal, Zsh)

% stack exec lesson-exe
Just 2 + Just 3 = Just 5
Just 2 + Nothing = Nothing
Nothing + Just 3 = Nothing
Nothing + Nothing = Nothing
%