How to handle undefined

I have a function that I would handle undefined in. Something like:

foo :: MyType -> State X ()
foo mt
    | isUndefined mt = do
        x .= undefined
        y .= undefined
foo (A a) = x .= a
foo (B b) = y .= b

However it generates a blackbox in the code because of catch method. How am I supposed to handle undefined?

Ok clashSimulation && hasUndefined mt seems to work

1 Like

It’s important to realize that checking if something is undefined is inherently a simulation time activity and will never actually work in hardware since there you will always have a value.

That being said, in Clash we typically use errorX or deepErrorX to create undefined expressions. These allow you to state the reason why that value is undefined. In your HDL they will also end up as undefined values which your synthesis tool can then “optimize away” by e.g. selecting an already existing valid value.

1 Like

In addition to what @lmbollen mentioned. Depending on what you actually want to achieve it might be more ergonomic to not set all fields undefined/errorXmanually but rather use `ensureSpine` at the location where you expect the spine to exist. For example if you have data X = X { x :: int, y :: int } then ensureSpine (errorX "Oops" :: X) becomes X { x = errorX "Oops" y = erroX "Oops" }.

It’s not entirely clear if that is your goal from the original message, but it smells to me like that is precisely what you want to do here.

1 Like

It’s important to realize that checking if something is undefined is inherently a simulation time activity and will never actually work in hardware since there you will always have a value.

Yes. See that my solution involve checking if it is simulation.

In my case if mt is undefined x and y are not used (don’t care). Which made me realize I probably should refactor code to make it more Haskelly using ADT but in my defense I haven’t used haskell in long time.

It’s not entirely clear if that is your goal from the original message, but it smells to me like that is precisely what you want to do here.

Yes. Except Clash use strict state so at point when I pattern match it’s already too late if I understand things correctly as it returns undefined on state level.