0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Haskellで集合を定義する

Posted at

Haskellを勉強中ですが、集合を扱いたいと思いました。しかし、リストについてはわかっているのですが、集合の場合はどうなるの?という疑問がわきました。
調べてみると、Setというのがありました。

集合には順序集合と非順序集合がある

インポートは以下のようにします。

import qualified Data.Set as Set

Setは順序付けられた集合で、非順序集合の場合は、HashSetを使うようです。

import qualified Data.HaseSEt as HashSet

速度なども影響するようです。

順序の集合

順序集合について例を示していきます。
順序集合の空集合、単一要素の集合、Listから集合をつくる場合は以下のようになります。

ghci> Set.empty
fromList []
ghci> Set.singleton 5
fromList [5]
ghci> Set.fromList [5, 3, 1, 2, 3]
fromList [1,2,3,5]

集合はList型にfromListというタグが付きます。
要素の重複が修正され、要素が順番に並ぶようになりますね。

階層化集合

\{\{1,2\},\{\{3,4\}\}\}

などのように集合の中に集合を使いたいので、階層化集合を定義します。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?