Search code examples
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)

Say I want to initialize some field (say line) with some ('()|void|#f|...) 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)]

But 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}. Is there any such "simple" way to express nil 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 graph build.

But I'm interested in the question in the general case, because I've bumped into this too many times now while writing in typed/racket...


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")