計算機科学のブログ

関数型プログラミングの基礎 リスト take関数、elem関数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 6(リスト)、6.5(練習問題)Q6-3の解答を求めてみる。

コード

lesson/app/Main.hs

module Main where

import Data.Bits (FiniteBits (finiteBitSize))
import Lib (inFirstHalf)

nums = [1 .. 10]

main :: IO ()
main = do
  print "偶数"
  mapM_ print $ (`inFirstHalf` nums) <$> nums
  print "奇数"
  mapM_ print $ (`inFirstHalf` nums) <$> [1 .. 11]

lesson/src/Lib.hs

module Lib
  ( inFirstHalf,
  )
where

inFirstHalf :: Eq a => a -> [a] -> Bool
inFirstHalf x xs =
  x `elem` take (length xs `div` 2) xs

入出力結果(Terminal, Zsh)

% stack build          
lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
lesson> build (lib + exe)
Preprocessing library for lesson-0.1.0.0..
Building library for lesson-0.1.0.0..
Preprocessing executable 'lesson-exe' for lesson-0.1.0.0..
Building executable 'lesson-exe' for lesson-0.1.0.0..
[2 of 2] Compiling Main
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/b6e8c918185b27e9dcbc52db0653ed10d7a4ac8a88584523c7314e6b50554430/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/b6e8c918185b27e9dcbc52db0653ed10d7a4ac8a88584523c7314e6b50554430/9.0.2/bin
Registering library for lesson-0.1.0.0..
% stack exec lesson-exe
"\20598\25968"
True
True
True
True
True
False
False
False
False
False
"\22855\25968"
True
True
True
True
True
False
False
False
False
False
False
%