Ninety-Nine Haskell Problems 6

1to10 11to20 21to30 31to40 51to60 61to70 71to80 81to90 91to99 all
Ninety-Nine Haskell Problems


六問目.

6 Problem 6

(*) Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x).

Example in Haskell:

*Main> isPalindrome [1,2,3]
False

*Main> isPalindrome "madamimadam"
True

*Main> isPalindrome [1,2,4,8,16,8,4,2,1]
True
http://www.haskell.org/haskellwiki/99_questions/1_to_10#Problem_6

リストが回文になってるかどうか示せ,と.
いいね,ちょっとずつライブラリっぽいところから離れてきた感じが.問題らしくなってきた.まぁ全然わからないんだけど.
さて,どうしよう.
いきなりとっかかる前に,とりあえずwhereが必要になりそうなので,試してみる.

test x y = InnerProduct x y (length x)
	where 
		InnerProduct _ _ 0 = 0
		InnerProduct (x:xs) (y:ys) n = x*y + InnerProduct xs ys (n-1)

これだと,

Undefined data constructor "InnerProduct"

とかいって,はじかれる.なんでだろうと思って色々試してみたら,どうやら,大文字で始めているのが問題っぽい.InnerProductをinnerProductに変えたらうまくいった.きっと,大文字で書くとコンストラクタで,関数は小文字から始めろってことかな.

  • コンストラクタは大文字から
  • 関数は小文字から


結構時間がかかったんだけど,結局この方法しか思いつかなかった.

isPalindrome :: Eq a => [a] -> Bool
isPalindrome x = x == (reverse x)

もとのリストとそれを逆転させたリストを比較するというもの.たぶんこれが一番単純な方法だと思う.今回はちゃんと,Eqクラスも含めて,型宣言をした.
ところで,リストを(==)で比較できるのが楽でよかった.(==)を用いない方法をやってみたのが次.

isPalindrome' :: Eq a => [a] -> Bool
isPalindrome' x = isEq x (reverse x) (length x)
	where
		isEq :: Eq a => [a] -> [a] -> Int -> Bool
		isEq x y 0 = True
		isEq (x:xs) (y:ys) n = (x == y) && isEq xs ys (n-1)

なんか,型宣言がちゃんとできるようになったのが嬉しい.
さて,解答.

Solution:
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome xs = xs == (reverse xs)

あらら,全く一緒だ.
ということで,六問目はこれでおしまい.

1to10 11to20 21to30 31to40 51to60 61to70 71to80 81to90 91to99 all
Ninety-Nine Haskell Problems