Is there any possibility, such as a language extension, to use the syntax of list comprehensions syntax for Data.Set
sets?
Example:
f :: Set a -> Set b -> Set (a,b)
f xs ys = [(x,y) | x <- xs , y <- ys] -- this is the set comprehension
Since sets are the mathematical structure that inspired list comprehensions it would be kind of strange not to have any possibility of using them on sets.
And yes, I am aware of MonadComprehensions
for using the list-comp syntax with any Monad
/ MonadPlus
type but AFAIK sets can't even be monads because of the Ord
constraint in most functions.
There are no language extensions which allow for "set comprehensions."
The differences between a Set
and a List
are:
Set
is unordered while the List
is ordered Set
are unique while the List
may have duplicate elements Set
is an instance of Ord
while the List
has no type restrictions. You can see that all possible Set
s are a strict subset of all possible List
s. This means that we can achieve "set comprehension" simply be using a list comprehension and converting it to a Set
. Lazy evaluation will often make the "set generation" efficient deriving from most finite list comprehensions. However, list comprehensions resulting in infinite lists are unlikely to result in efficient "set comprehension."
Example:
import Data.Set
set :: Ord a => Set a
set = fromList [x * y | x <- [1..10], y <- [1..10]]
Using the set-monad
package, you can define a Set
as an instance of Monad
and using the language extension MonadComprehensions
you can achieve a "set comprehension".
Example:
{-# LANGUAGE MonadComprehensions #-}
import Data.Set.Monad
set1 :: Set (Int,Int)
set1 = do
a <- fromList [1 .. 4]
b <- fromList [1 .. 4]
return (a,b)
-- Look a "set comprehension"
set2 :: Set (Int,Int)
set2 = [ (a,b) | (a,b) <- set1, even a, even b ]
Use whichever method makes the most sense for your project. Profile both before making a decision!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.