Home > Software design >  How can I generate a null type in Haskell?
How can I generate a null type in Haskell?

Time:11-10

I need to make a Quadtree in Haskell. But I never used the language before. As I understand, there is no null pointers in Haskell. So how could I instantiate a null version of Group for the pointers of the Quadtree(if there is even a way)?

data Group = Group {
    idf :: Int,
    name :: String,
    lat :: Int,
    long :: Int,
    nw :: Group,
    ne :: Group,
    sw :: Group,
    se :: Group
} deriving Show

main :: IO()

main = do
    let g1 = Group { idf = 0, name = "Ababa", lat = 32, long = 40, nw = ???}
    print g1

I know Maybe exists. No idea how to use it in this context though.

CodePudding user response:

You use Maybe. It's a type that can have values of two different kinds: either Nothing or Just x where x is a value of some other type.

data Group = Group {
    ...
    nw :: Maybe Group,
    ne :: Maybe Group,
    sw :: Maybe Group,
    se :: Maybe Group
} deriving Show

main = do
    let g1 = Group { ..., nw = Nothing, ne = Nothing, sw = Nothing, se = Nothing }
    print g1

    ...

    let g2 = Group { ... ne = Just g1, ... }

CodePudding user response:

I would add a constructor to your Group.

data Group = Empty | Group {
    idf :: Int,
    name :: String,
    lat :: Int,
    long :: Int,
    nw :: Group,
    ne :: Group,
    sw :: Group,
    se :: Group
    } deriving Show

Usually it's a bad sign if you're using record syntax in a type with multiple constructors, so you may want to educate yourself on the pitfalls.

  • Related