計算機科学のブログ

関数型プログラミングの基礎 高階関数 リストのフィルタリング filter関数、remove関数の実装

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 9(高階関数)、9.3(リストのフィルタリング)、クイックチェック 9-1の解答を求めてみる。

コード

lesson/app/Main.hs

module Main where

import Lib (remove, remove1)

ns = [1 .. 10]

main :: IO ()
main = do
  mapM_ print $
    [ ns,
      remove even ns,
      remove odd ns,
      remove1 even ns,
      remove1 odd ns
    ]

lesson/src/Lib.hs

module Lib
  ( remove,
    remove1,
  )
where

remove :: (a -> Bool) -> [a] -> [a]
remove _ [] = []
remove test (x : xs) =
  if test x
    then remove test xs
    else x : remove test xs

remove1 :: (t -> Bool) -> [t] -> [t]
remove1 test = filter (not . test)

入出力結果(Terminal, Zsh)

% stack build          
lesson-0.1.0.0: unregistering (local file changes: src/Lib.hs)
lesson> build (lib + exe)
Preprocessing library for lesson-0.1.0.0..
Building library for lesson-0.1.0.0..
[2 of 2] Compiling Lib
Preprocessing executable 'lesson-exe' for lesson-0.1.0.0..
Building executable 'lesson-exe' for lesson-0.1.0.0..
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/lesson-exe/lesson-exe ...
lesson> copy/register
Installing library in /Users/…/lesson/.stack-work/install/x86_64-osx/494c7f11ebc566ca0dd51f0cf6ed1f4268c15f68d59cb48ce0d42f2bf991d579/9.0.2/lib/x86_64-osx-ghc-9.0.2/lesson-0.1.0.0-CIOIkpTgcfQI9akDJnwnSd
Installing executable lesson-exe in /Users/…/lesson/.stack-work/install/x86_64-osx/494c7f11ebc566ca0dd51f0cf6ed1f4268c15f68d59cb48ce0d42f2bf991d579/9.0.2/bin
Registering library for lesson-0.1.0.0..
% stack exec lesson-exe
[1,2,3,4,5,6,7,8,9,10]
[1,3,5,7,9]
[2,4,6,8,10]
[1,3,5,7,9]
[2,4,6,8,10]
%