3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Haskellドリル(リスト編)解答例

Posted at

課題1

指示

リストの最後の要素を取得する関数 myLast を作れ。
ただし、再帰を用いること。

Prelude> myLast [1, 2, 3, 4]
4

解答例

myLast.hs
myLast 			:: [a] -> a
myLast			= f where
	f []		= error "No last for empty list"
	f [x]		= x
	f (_ : xs)	= f xs

課題2

指示

リストの最後の要素を取得する関数 myLast を作れ。
ただし、再帰を用いず、Prelude にある関数を合成して作成すること。

Prelude> myLast [1, 2, 3, 4]
4

解答例

myLast2.hs
myLast 	:: [a] -> a
myLast	= head . reverse

課題3

指示

リストの n 番目の要素を取得する関数 myIndex を作れ。

Prelude> myIndex [1, 2, 3, 4] 2
2
Prelude> myIndex [1, 2, 3, 4] 3
3

解答例

myIndex.hs
myIndex					:: [a] -> Int -> a
myIndex					= f where
	f [] _				= error "too large index"
	f (x : xs) n
		| n == 0		= x
		| n > 0			= f xs (n - 1)
		| otherwise	= error "negative index"

課題4

指示

与えられた文字列を全て大文字に変える関数 myUpper を作れ。

Prelude> myUpper "aBcDeFghi"
ABCDEFGHI

解答例

myUpper.hs
myUpper     :: String -> String
myUpper     = map toUpper

課題5

指示

与えられた整数リストのうち、奇数だけの合計値を求めるoddSumを作れ。
ただし、foldlfilterを合成して作成すること。

Prelude> oddSum [1,2,3,4,5,8,9,11]
29

解答例

oddSum.hs
oddSum		:: [Int] -> [Int]
oddSum		= foldl (+) 0 . filter odd

課題6

指示

与えられたテキストファイルに行番号を付与する関数 lineNum を作れ。
ただし、行番号の桁揃えなどを行わなくて良い。

解答例

lineNum.hs
lineNum			:: [String] -> [String]
lineNum			= f where
	f			= map g . zip [1..]
	g (ln, st)	= show ln ++ " " ++ st
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?