コンテキストでの型の操作 Functor型クラス Functorはいつもそばにいる リスト、fmap関数とmap関数、<$>演算子
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON 27(Functor型クラス)、27.3(Functorはいつもそばにいる)、RobotPartのリストをHTMLのリストに変換する、クイックチェック 27-3の解答を求めてみる。
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 qualified Data.Map as Map
import Lib
leftArm :: RobotPart
leftArm =
RobotPart
{ name = "left arm"
}
rightArm :: RobotPart
rightArm =
RobotPart
{ name = "right arm"
}
robotHead :: RobotPart
robotHead =
RobotPart
{ name = "robot head"
}
partsDB :: Map.Map Int RobotPart
partsDB =
Map.fromList $
zip
[1, 2, 3]
[leftArm, rightArm, robotHead]
allParts :: [RobotPart]
allParts = snd <$> Map.toList partsDB
main :: IO ()
main = do
print partsDB
print $ Map.toList partsDB
print allParts
lesson/src/Lib.hs
module Lib where
data RobotPart = RobotPart
{ name :: String
}
deriving (Show)
入出力結果(Terminal, Zsh)
% stack exec lesson-exe
fromList [(1,RobotPart {name = "left arm"}),(2,RobotPart {name = "right arm"}),(3,RobotPart {name = "robot head"})]
[(1,RobotPart {name = "left arm"}),(2,RobotPart {name = "right arm"}),(3,RobotPart {name = "robot head"})]
[RobotPart {name = "left arm"},RobotPart {name = "right arm"},RobotPart {name = "robot head"}]
%