計算機科学のブログ

コンテキストでの型の操作 Functor型クラス インスタンス化、fmap関数、リスト、変換

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT5(コンテキストでの型の操作)、LESSON 27(Functor型クラス)、27.5(練習問題)Q27-1の解答を求めてみる。

コード

data Box a = Box a deriving Show

instance Functor Box where
    fmap f (Box x) = Box (f x)

box :: Box String
box = Box "present"

n :: Int
n = 5

morePresents :: Box a -> Int -> Box [a]
morePresents box n = fmap (\x -> take n (repeat x)) box

-- 以下Visual Studio Code ExtentionのHSL(Haskell Language Serverが教えてくれた。)
-- 部分適用
morePresents1 :: Int -> Box a -> Box [a]
morePresents1 n = fmap (\x -> take n (repeat x))

-- ラムダ関数を除去
morePresents2 :: Int -> Box a -> Box [a]
morePresents2 n = fmap (take n . repeat)

-- take関数、repeat関数をreplicate関数の置き換え
morePresents3 :: Int -> Box a -> Box [a]
morePresents3 n = fmap (replicate n)

main :: IO ()
main = do
    print box
    print (morePresents box n)
    print (morePresents1 n box)
    print (morePresents2 n box)
    print (morePresents3 n box)

入出力結果(Terminal, Zsh)

% runghc sample1.hs 
Box ["present","present","present","present","present"]
Box ["present","present","present","present","present"]
% runghc sample1.hs
Box "present"
Box ["present","present","present","present","present"]
Box ["present","present","present","present","present"]
% runghc sample1.hs
Box "present"
Box ["present","present","present","present","present"]
Box ["present","present","present","present","present"]
% runghc sample1.hs
Box "present"
Box ["present","present","present","present","present"]
Box ["present","present","present","present","present"]
Box ["present","present","present","present","present"]
Box ["present","present","present","present","present"]
%