関数型プログラミングの基礎 高階関数 リストのフィルタリング、要素の削除、リストの畳み込み、総乗
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 9(高階関数)、9.3(リストのフィルタリング)のクイックチェック9-1、9.4(リストの畳み込み)のクイックチェック9-2の解答を求めてみる。
コード
-- クイックチェック9-1
remove :: (a -> Bool) -> [a] -> [a]
remove _ [] = []
remove test (x : xs) =
if test x
then remove test xs
else x : remove test xs
-- クイックチェック9-2
myProduct :: (Foldable t, Num b) => t b -> b
myProduct xs = foldl (*) 1 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
λ> :load sample01
[1 of 1] Compiling Main ( sample01.hs, interpreted )
Ok, one module loaded.
(0.01 secs,)
*Main
λ> remove even []
[]
it :: Integral a => [a]
(0.11 secs, 63,048 bytes)
*Main
λ> remove even [1]
[1]
it :: Integral a => [a]
(0.00 secs, 61,992 bytes)
*Main
λ> remove even [2]
[]
it :: Integral a => [a]
(0.00 secs, 61,088 bytes)
*Main
λ> remove even [1..10]
[1,3,5,7,9]
it :: Integral a => [a]
(0.01 secs, 71,472 bytes)
*Main
λ> :load sample01
[1 of 1] Compiling Main ( sample01.hs, interpreted )
sample01.hs:10:14: error:
Not in scope: type constructor or class ‘GHC.Types.Any’
No module named ‘GHC.Types’ is imported.
|
10 | myProduct :: GHC.Types.Any Integer -> Integer
| ^^^^^^^^^^^^^
Failed, no modules loaded.
(0.03 secs,)
Prelude
λ> :load sample01
[1 of 1] Compiling Main ( sample01.hs, interpreted )
sample01.hs:10:13: error:
• Ambiguous type variable ‘t0’ arising from a use of ‘foldl’
prevents the constraint ‘(Foldable t0)’ from being solved.
Relevant bindings include
myProduct :: t0 Integer -> Integer (bound at sample01.hs:10:1)
Probable fix: use a type annotation to specify what ‘t0’ should be.
These potential instances exist:
instance Foldable (Either a) -- Defined in ‘Data.Foldable’
instance Foldable Maybe -- Defined in ‘Data.Foldable’
instance Foldable ((,) a) -- Defined in ‘Data.Foldable’
...plus one other
...plus 26 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: foldl (*) 1
In an equation for ‘myProduct’: myProduct = foldl (*) 1
|
10 | myProduct = foldl (*) 1
| ^^^^^^^^^^^
Failed, no modules loaded.
(0.07 secs,)
Prelude
λ> :load sample01
[1 of 1] Compiling Main ( sample01.hs, interpreted )
Ok, one module loaded.
(0.00 secs,)
*Main
λ> myProduct []
1
it :: Num b => b
(0.04 secs, 59,784 bytes)
*Main
λ> myProduct [1]
1
it :: Num b => b
(0.00 secs, 59,904 bytes)
*Main
λ> myProduct [2
<interactive>:11:13: error:
parse error (possibly incorrect indentation or mismatched brackets)
*Main
λ> myProduct [2]
2
it :: Num b => b
(0.00 secs, 59,904 bytes)
*Main
λ> myProduct [2, 3]
6
it :: Num b => b
(0.00 secs, 60,040 bytes)
*Main
λ> myProduct [1..10]
3628800
it :: (Num b, Enum b) => b
(0.00 secs, 65,608 bytes)
*Main
λ> :quit
Leaving GHCi.
%