9
3

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の無限リスト系関数

Last updated at Posted at 2018-03-08

頻繁にどれがどれだか分からなくなるので、まとめ。

infnite.hs
repeat :: a -> [a]
take 5 $ repeat 3
-- [3,3,3,3,3]

replicate :: Int -> a -> [a]
replicate 5 3
-- [3,3,3,3,3]

cycle :: [a] -> [a]
take 10 $ cycle [1,2]
-- [1,2,1,2,1,2,1,2,1,2]

iterate :: (a -> a) -> a -> [a]
take 5 $ iterate (^2) 2
-- [2,4,16,256,65536]
  • repeatは単一要素からなる無限リストを生成
  • replicaterepeatの有限版(要素数はInt
  • cycleはリストを繰り返しによって無限に拡張する(repeatのリスト版と思っていい)
  • iterateは前要素に順に関数を適用してリストを生成する

これらは全て初期値からのリスト生成となるのでunfoldrで実装可能
(もちろん再帰でも書けるが自明なので省略)

上の例をunfoldrで書き換える.hs
-- repeat,replicate
-- replicateはNothingを用いて書くことも可
take 5 $ unfoldr (\x -> Just(x,x)) 3
-- cycle
take 10 . concat $ unfoldr (\xs -> Just(xs,xs)) [1,2]
-- iterate
take 5 $ unfoldr (\x -> Just(x,x^2)) 2

iteratexに関数を適用して次の要素生成に回すが、他もid xと考えれば同形式となる

9
3
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
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?