Summary: Generic function that collects all values of a specified type from a
generic value.
collect works by searching a datatype for values that are the same type as
the return type specified. Here are some examples using the same value but
different return types:
GHCi> collect [Just 1, Nothing, Just (2 :: Int)] :: [Int]
[1,2]
GHCi> collect [Just 1, Nothing, Just (2 :: Int)] :: [Maybe Int]
[Just 1,Nothing,Just 2]
GHCi> collect [Just 1, Nothing, Just (2 :: Int)] :: [[Maybe Int]]
[[Just 1,Nothing,Just 2]]
Note that the number 2 has the type Int. Some arguments (such as numeric
constants which have type Num a => a) may need explicit type annotations.
By design, there is no connection that can be inferred between the return
type and the argument type.
collect only works if the return type has been made an instance of Rep.
The library provides instances for all datatypes with included
representation.
An instance is trivial to write. Given a type D, the Rep instance looks
like this:
{-# LANGUAGE OverlappingInstances #-}
data D = ...
instance Rep (Collect D) D where
rep = Collect (:[])
(Note the requirement of overlapping instances.) This instance triggers when
the result type (the first D) matches some value type (the second D)
contained within the argument to collect. See the source of this module for
more examples.
|