計算機科学のブログ

型の紹介 型の基礎 filter関数とmap関数の型シグネチャ

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT2(型の紹介)、LESSON11(型の基礎)、11.2(練習問題)Q11-1の解答を求めてみる。

コード

--自身で実装してみて型を確認
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter _ [] = []
myFilter f (x : xs) =
  if f x
    then x : myFilter f xs
    else myFilter f xs

myMap :: (a -> b) -> [a] -> [b]
myMap _ [] = []
myMap f (x : xs) = f x : myMap f xs

ns :: [Integer]
ns = [-5 .. 5]

main :: IO ()
main = do
  print "filter even"
  print $ myFilter even ns
  print $ filter even ns
  print "map (* 2)"
  print $ myMap (* 2) ns
  print $ map (* 2) ns

入出力結果(Terminal, Zsh)

% runghc sample1.hs 
"filter even"
[-4,-2,0,2,4]
[-4,-2,0,2,4]
"map (* 2)"
[-10,-8,-6,-4,-2,0,2,4,6,8,10]
[-10,-8,-6,-4,-2,0,2,4,6,8,10]
% ghci
GHCi, version 8.10.7: https://www.haskell.org/ghc/  :? for help
Loaded package environment from /Users/…/.ghc/x86_64-darwin-8.10.7/environments/default
macro 'doc' overwrites builtin command.  Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /Users/kamimura/.ghc/ghci.conf
Prelude
λ> :t filter
filter :: (a -> Bool) -> [a] -> [a]
Prelude
λ> :t map
map :: (a -> b) -> [a] -> [b]
Prelude
λ> :quit
Leaving GHCi.
%