nullracketvoidtyped-racket

Is there an idiomatic way of expressing Null in typed racket?


I want to define a type using struct in Typed Racket. For example :

(struct a-node 
    ([line : ProgLine]
    [latency : Integer]
    [pred-edges : (List Edge)]
    [succ-edges : (List Edge)])
    #:mutable
    #:type-name Node)

Suppose I want to initialize a field (eg line) with some 'null' value, and then update the field (a-node-line) later on. I've looked for an idiomatic way, in general on search engines, and likewise, here, and I have not found a satisfactory answer. I've tried for example:

[line : (U ProgLine Void)]

However that results in awkward code. I've played with using a maybe monad, but that's also not what I'm looking for. It's great for some use cases, but sometimes it is not apt. I've written a good amount of Scheme (where one would express #f or '()), but not too much Racket. My background with statically typed languages falls in the C family, where one would express NULL, nullptr, etc. What is the idiomatic way to express "null" for pointer variables in Typed Racket?

For context, I'm building a scheduler for the back-end of a compiler and a Node is used for nodes in the dependency graph. These Node structures will be the sentinels / list heads for a vector of adjacency lists for an adjacency list representation (bi-directional). I build the graph in a linear pass over the program IR. Before the top->bottom traversal of the IR, I want to initialize the adjacency vector, and then update the Node structures during the build.


Solution

  • The idiomatic way is to use an Option type, which you can find in the docs here.

    Note that this essentially amounts to using #f as your "null" version of the value. Racket also has the nice property that any value other than #f is truthy, so we can check for "null-ness" by doing:

    (if my-value
       "value-case"
       "null-case")