Los conjuntos en Haskell (Data.Set)

1 Introducción

ghci> import Data.Set as S
import qualified Data.Set as S

2 El tipo de los conjuntos

ghci> c1 = fromList [3,2,5,3]
ghci> :type c1
c1 :: (Ord a, Num a) => Set a
ghci> c1
fromList [2,3,5]
ghci> c2 = fromList [2,5,2,3]
ghci> c1 == c2
True

3 Resumen de funciones básicas

ghci> empty
fromList []
ghci> insert 7 (fromList [3,2,5])
fromList [2,3,5,7]
ghci> insert 2 (fromList [3,2,5])
fromList [2,3,5]
ghci> delete 3 (fromList [3,2,5,3,4])
fromList [2,4,5]
ghci> delete 7 (fromList [3,2,5,3,4])
fromList [2,3,4,5]
ghci> member 5 (fromList [3,2,5])
True
ghci> member 7 (fromList [3,2,5])
False
ghci> S.null (fromList [])
True
ghci> S.null (fromList [5,2])
False

4 Otras funciones sobre conjuntos

4.1 De listas a conjuntos

ghci> fromList [3,2,5,2,15]
fromList [2,3,5,15]
ghci> :t it
it :: (Ord a, Num a) => Set a

4.2 De conjuntos a listas

ghci> elems (fromList [3,2,5,2,1,5])
[1,2,3,5]
ghci> toList (fromList [3,2,5,2,1,5])
[1,2,3,5]

4.3 Operaciones y relaciones usuales

ghci> union (fromList [3,2,5]) (fromList [2,7,5])
fromList [2,3,5,7]
ghci> intersection (fromList [3,2,5]) (fromList [2,7,5])
fromList [2,5]
ghci> difference (fromList [2,5,3]) (fromList [1,4,5])
fromList [2,3]
ghci> fromList [2,5,3] \\ fromList [1,4,5]
fromList [2,3]
ghci> size (fromList [3,2,5,3,2,1])
4
ghci> isSubsetOf (fromList [3,5]) (fromList [3,2,5]) 
True
ghci> isSubsetOf (fromList [3,5,2]) (fromList [3,2,5]) 
True
ghci> isProperSubsetOf (fromList [3,7]) (fromList [3,2,5]) 
False
ghci> isProperSubsetOf (fromList [3,5]) (fromList [3,2,5]) 
True
ghci> isProperSubsetOf (fromList [3,5,2]) (fromList [3,2,5]) 
False
ghci> isProperSubsetOf (fromList [3,7]) (fromList [3,2,5]) 
False
ghci> fromList [3,2,5] == fromList [5,2,3,2]
True
ghci> fromList [3,2,5] == fromList [5,1,3,2]
False
ghci> S.map (+2) (fromList [3,2,7])
fromList [4,5,9]
ghci> S.filter even (fromList [3,2,5,7,8,6,9])
fromList [2,6,8]

5 Funciones sobre conjuntos

6 Referencia



Universidad de Sevilla

José A. Alonso Jiménez
Grupo de Lógica Computacional
Dpto. de Ciencias de la Computación e I.A.
Universidad de Sevilla