型の紹介 型の基礎 型シグネチャ、filter関数とmap関数、リスト、空のリストでエラーにならないtail関数の作成、foldl関数
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT2(型の紹介)、LESSON 11(型の基礎)、11.5(練習問題)Q11-1の解答を求めてみる。
コード
-- Q11-1
-- filter:: (a -> Bool) -> [a] -> [a]
-- map:: (a -> b) -> [a] -> [b]
-- Q11-2
-- 空のリストを返すtail関数の作成は可能
myTail :: [a] -> [a]
myTail [] = []
myTail (x:xs) = xs
-- 空のリストを返すhead関数の作成は不可能
-- その理由はリストの型シグネチャを[a]とすると、戻り値の型がaと[a]になるから
-- Q11-3
myFoldl :: (a -> b -> a) -> a -> [b] -> a
myFoldl f init [] = init
myFoldl f init (x:xs) = myFoldl f (f init x) xs
入出力結果(Terminal, Zsh)
% 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
λ> :t filter
filter :: (a -> Bool) -> [a] -> [a]
Prelude
λ> :t map
map :: (a -> b) -> [a] -> [b]
Prelude
λ> tail []
*** Exception: Prelude.tail: empty list
Prelude
λ> :load sample1
[1 of 1] Compiling Main ( sample1.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> :load sample1
[1 of 1] Compiling Main ( sample1.hs, interpreted )
Ok, one module loaded.
(0.00 secs,)
*Main
λ> myTail []
[]
it :: [a]
(0.00 secs, 60,648 bytes)
*Main
λ> myTail [1]
[]
it :: Num a => [a]
(0.00 secs, 60,752 bytes)
*Main
λ> myTail [1,2]
[2]
it :: Num a => [a]
(0.00 secs, 61,520 bytes)
*Main
λ> myTail [1..10]
[2,3,4,5,6,7,8,9,10]
it :: (Num a, Enum a) => [a]
(0.01 secs, 75,216 bytes)
*Main
λ> :load sample1
[1 of 1] Compiling Main ( sample1.hs, interpreted )
Ok, one module loaded.
(0.00 secs,)
*Main
λ> :load sample1
[1 of 1] Compiling Main ( sample1.hs, interpreted )
Ok, one module loaded.
(0.00 secs,)
*Main
λ> :t foldl
foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b
*Main
λ> myFoldl (+) 1.5 [1..10]
56.5
it :: (Fractional a, Enum a) => a
(0.00 secs, 67,424 bytes)
*Main
λ> :quit
Leaving GHCi.
%