Tuesday, December 6, 2016

Getting Started with Haskell Data.Set datatype

Here is an example of how to use the Haskell Data.Set datatype.  I had not used list comprehensions in Haskell before either, and I conclude that they are super cool!


-- SetExample.hs
--
--
-- compilation:
--      ghc --make SetExample.hs -o setExample
--
-- usage:
--      ./setEx 
--
-- Reference:
-- https://downloads.haskell.org/~ghc/6.12.3/docs/html/libraries/containers-0.3.0.0/Data-Set.html#7
--


module Main where

import System.IO

import Data.Set (Set)
import qualified Data.Set as Set

main = do

    -- creating an empty set
    let s1 = Set.empty :: Set Int
    print s1
    
    -- Some basic set operations.
    let s2 = Set.singleton 42
    print s2
    let s3 = Set.union s2 (Set.fromList [7,8,9])
    print (Set.elems s3)
    
    -- using a list comprehension with a set
    let x1 = [ (x,y) | x <- (Set.toList s2), y <- (Set.toList s3)]
    print x1