コンテキストでの型の操作 Monad型クラス ApplicativeとFunctorの制限 2つのMap.lookupを組み合わせる pure関数
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON 30(Monad型クラス)、30.1(ApplicativeとFunctorの制限)、2つのMap.lookupを組み合わせる、クイックチェック 30-1の解答を求めてみる。
得られる結果がMaybe PlayerCredits型ではなく、Maybe (Maybe PlayerCredits)型になってしまう。
実際に確認。
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
ghc-options:
- -Wall
- -Wcompat
- -Widentities
- -Wincomplete-record-updates
- -Wincomplete-uni-patterns
- -Wmissing-export-lists
- -Wmissing-home-modules
- -Wpartial-fields
- -Wredundant-constraints
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 (main) where
import Lib
( creditsFromIdStrange,
)
main :: IO ()
main = do
mapM_ (print . creditsFromIdStrange) [0 .. 4]
lesson/src/Lib.hs
module Lib
( creditsFromIdStrange,
)
where
import qualified Data.Map as Map
type UserName = String
type GamerId = Int
type PalyerCredits = Int
userNameDB :: Map.Map GamerId String
userNameDB =
Map.fromList
[ (1, "name1"),
(2, "name2")
]
creditsDB :: Map.Map String PalyerCredits
creditsDB =
Map.fromList
[ ("name1", 2000),
("name2", 15000)
]
lookupUserName :: GamerId -> Maybe UserName
lookupUserName gamerId = Map.lookup gamerId userNameDB
lookupCredits :: UserName -> Maybe PalyerCredits
lookupCredits username = Map.lookup username creditsDB
creditsFromIdStrange :: GamerId -> Maybe (Maybe PalyerCredits)
creditsFromIdStrange gamerId =
pure lookupCredits
<*> lookupUserName gamerId
入出力結果(Terminal, Zsh)
% stack exec lesson-exe
Nothing
Just (Just 2000)
Just (Just 15000)
Nothing
Nothing
%