計算機科学のブログ

型によるプログラミング Maybe型:欠損値に対処する Maybeを使った計算 JustとNothing、パターン、関数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT3(型によるプログラミング)、LESSON 19(Maybe型:欠損値に対処する)、19.3(Maybeを使った計算)、クイックチェック 19-2の解答を求めてみる。

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
- containers

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

maybeNums :: [Maybe Int]
maybeNums =
  mconcat
    [ [Nothing],
      map Just [1 .. 5],
      [ Nothing,
        Just 0,
        Nothing
      ]
    ]

nums :: [Int]
nums = map numOrZero maybeNums

main :: IO ()
main = do
  print maybeNums
  print nums
  print $ zip maybeNums nums

lesson/src/Lib.hs

module Lib where

numOrZero :: Maybe Int -> Int
numOrZero (Just n) = n
numOrZero Nothing = 0

入出力結果(Terminal, Zsh)

% stack exec lesson-exe
[Nothing,Just 1,Just 2,Just 3,Just 4,Just 5,Nothing,Just 0,Nothing]
[0,1,2,3,4,5,0,0,0]
[(Nothing,0),(Just 1,1),(Just 2,2),(Just 3,3),(Just 4,4),(Just 5,5),(Nothing,0),(Just 0,0),(Nothing,0)]
%