Question

I am trying to build the graph ADT in Haskell. I don't know how to get the default value for a generic type.

type Node = Int
type Element a = (Node, a, [Int]) --Node: ID; a: generic value; [Int]: adjancent nodes' IDs
type Graph a = [Element a]
insNode :: Graph a -> Node -> Graph a
insNode g n = g ++ [(n,?,[])]

What do I have to write in place of ? in order to get the default value for type a? Many thanks in advance!

Was it helpful?

Solution

You can't. There's no way to magically create an value of any type.

There's undefined :: a, but if ever evaluated this will crash your program. Instead, I'd suggest either

type Element a = (Node, Maybe a, [Int]) -- It's optional to have a value

or

insNode :: a -> Node -> Graph a -> Graph a
-- Optional idea, use `Data.Default` to ease the typing burden
defInsNode :: Def a => Node -> Graph a -> Graph a
defInsNode = insNode def

With the first option you can just stick Nothing in there (which is really what you have), or with the second option you just require the user to provide a value.

Finally a style note, instead of synonyms for tuples, I'd suggest using

type Node = Int
data Element a = Element { node :: Node
                         , val  :: Maybe a
                         , edges :: [Node]}
               deriving (Eq, Show)

Now you construct these Elements with Element node val edges and can pattern match in much the same way. Tuples of more than 2 elements are usually the wrong way to go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top