Real World Haskell
実戦で学ぶ関数型言語プログラミング
Bryan O'Sullivan, John Goerzen, Don Stewart(著)
山下 伸夫, 伊東 勝利
株式会社タイムインターメディア(翻訳)
開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- プログラミング言語: Haskell (純粋関数型)
Real World Haskell』(Bryan O'Sullivan、John Goerzen、Don Stewart(著)、山下 伸夫、伊東 勝利、株式会社タイムインターメディア(翻訳)、オライリー・ジャパン、2009年、ISBN978-4-87311-423-3)の3章(型を定義し、関数を単純化する)の3.13(ガード条件節の評価)の練習問題5.を解いてみる。
5.
コード(BBEdit)
Sample.hs
-- file: sample.hs
kaibun :: [a] -> [a]
--isKaibun :: [a] -> Bool
-- 上記だとエラーになった。試しに関数の型の定義をしないで実行したら上手くいった。
-- :type で型を調べてみたら、以下のようになっていた。「==」を使うためにいるみたい。
-- たぶんまだ出てきてないけど、この先でてくるのかな。
-- 既知の知識だけで、「==」を使わないで済む方法を考えてみたけど思いつかず。。
isKaibun :: Eq a => [a] -> Bool
kaibun [] = []
kaibun (x:xs) = x : kaibun xs ++ [x]
isKaibun [] = True
isKaibun (_:[]) = False
isKaibun (x:xs) = x == last xs && isKaibun a
where a = take (length xs - 1) xs
入出力結果(Terminal)
$ ghci
GHCi, version 7.4.2: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> :load Sample.hs
[1 of 1] Compiling Main ( Sample.hs, interpreted )
Sample.hs:12:21:
No instance for (Eq a)
arising from a use of `=='
In the first argument of `(&&)', namely `x == last xs'
In the expression: x == last xs && isKaibun a
In an equation for `isKaibun':
isKaibun (x : xs)
= x == last xs && isKaibun a
where
a = take (length xs - 1) xs
Failed, modules loaded: none.
Prelude> :load Sample.hs
[1 of 1] Compiling Main ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> :type isKaibun
isKaibun :: Eq a => [a] -> Bool
*Main> :load Sample.hs
[1 of 1] Compiling Main ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> kaibun [1,2,3,4,5]
[1,2,3,4,5,5,4,3,2,1]
*Main> isKaibun it
True
*Main> kaibun "haskell"
"haskelllleksah"
*Main> isKaibun it
True
*Main> isKaibun [1,2,3,2,1]
False
*Main> isKaibun [1,2,3,4,5]
False
*Main> isKaibun "abba"
True
*Main> isKaibun []
True
*Main> kaibun []
[]
*Main> isKaibun [1]
False
*Main> isKaibun 1
<interactive>:16:10:
No instance for (Num [a0])
arising from the literal `1'
Possible fix: add an instance declaration for (Num [a0])
In the first argument of `isKaibun', namely `1'
In the expression: isKaibun 1
In an equation for `it': it = isKaibun 1
*Main> isKaibun "a"
False
*Main> isKaibun "abba"
True
*Main> :quit
Leaving GHCi.
$
0 コメント:
コメントを投稿