計算機科学のブログ

関数型プログラミングの基礎 高階関数 filter関数とlength関数によるelem関数の定義、回文、map関数、大文字と小文字の変換、スペース削除、調和級数、遅延評価

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 9(高階関数)、9.6(練習問題)、Q9-1、Q9-2、Q9-3の解答を求めてみる。

コード

import Data.Char ( toLower )


-- Q9-1
myElem :: Eq a => a -> [a] -> Bool
myElem x xs = length (filter (== x) xs) /= 0

-- Q9-2
isPalindrome x =
    let y = map toLower (filter (/= ' ') x)
    in y == reverse y

-- Q9-3
terms :: Fractional a => [a] -> [a] -> [a]
terms [] _ = []
terms _ [] = []
terms (x:xs) (y:ys) = x/y:terms xs ys


harmonic n =
    let nums = repeat 1
        dens = [1..]
        ts = take n (terms nums dens)
    in foldr (+) 0 ts

入出力結果(Terminal, Zsh)

\kamimura@iMac lesson9 % ghci
GHCi, version 8.10.4: https://www.haskell.org/ghc/  :? for help
macro 'doc' overwrites builtin command.  Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /.../.ghc/ghci.conf
Prelude
λ> :load sample1
[1 of 1] Compiling Main             ( sample1.hs, interpreted )
Ok, one module loaded.
(0.17 secs,)
*Main
λ> elem 1 []
False
it :: Bool
(0.22 secs, 65,120 bytes)
*Main
λ> elem 1 [1]
True
it :: Bool
(0.00 secs, 62,064 bytes)
*Main
λ> elem 1 [1..10]
True
it :: Bool
(0.01 secs, 61,840 bytes)
*Main
λ> elem 1 [2..10]
False
it :: Bool
(0.00 secs, 63,128 bytes)
*Main
λ> elem 1 [2, 1, 10]
True
it :: Bool
(0.00 secs, 61,840 bytes)
*Main
λ> myElem 1 []
False
it :: Bool
(0.00 secs, 62,600 bytes)
*Main
λ> myElem 1 [1]
True
it :: Bool
(0.03 secs, 62,000 bytes)
*Main
λ> myElem 1 [1..10]
True
it :: Bool
(0.00 secs, 62,744 bytes)
*Main
λ> myElem 1 [2..10]
False
it :: Bool
(0.00 secs, 63,312 bytes)
*Main
λ> myElem 1 [2, 1, 10]
True
it :: Bool
(0.00 secs, 62,080 bytes)
*Main
λ> :load sample1
[1 of 1] Compiling Main             ( sample1.hs, interpreted )
Ok, one module loaded.
(0.05 secs,)
*Main
λ> isPalindrome "A man a plan a canal Panama"
True
it :: Bool
(0.00 secs, 68,368 bytes)
*Main
λ> :load sample1
[1 of 1] Compiling Main             ( sample1.hs, interpreted )
Ok, one module loaded.
(0.05 secs,)
*Main
λ> harmonic 1
1.0
it :: (Enum b, Fractional b) => b
(0.01 secs, 63,800 bytes)
*Main
λ> harmonic 2
1.5
it :: (Enum b, Fractional b) => b
(0.00 secs, 64,280 bytes)
*Main
λ> map harmonic [1..10]
[1.0,1.5,1.8333333333333333,2.083333333333333,2.283333333333333,2.45,2.5928571428571425,2.7178571428571425,2.828968253968254,2.9289682539682538]
it :: (Enum b, Fractional b) => [b]
(0.00 secs, 254,608 bytes)
*Main
λ> :quit
Leaving GHCi.
%