0

I am working with a Haskell libraby that discribes digital circuits (Lava), its function inputs and outputs are of the type signal ( Signal Bool , Signal Int) , as far as i know there is not a function that converts from a Signal Int to Int, I know there are several arithmetic operations that we can use with the type Signal Int, but not all arithmetic operations are possible. I wrote this function that is suppose to convert from Signal Int to Int ( just for the values that I need).

signalInt2int :: Signal Int -> Int
signalInt2int x = case x of 
    0 -> 0 
    1 -> 1 
    15 -> 15 
    _ -> 1000

Just for trying I only wrote these 4 possibilities, the problem is whenever I call this function no matter what the input is, the output is always 1000. I make sure to use an input of the type Signal Int. Here is what I get.

enter image description here

Can anyone point out where the problem is? I will be grateful for your help.

Balkis
  • 103
  • 7
  • your input `x` will never match `0` nor `1` nor `15` because `x` is a list not a number, so you are matching against `_` which returns `1000`. Actually I think it should not compile? – lsmor Nov 28 '18 at 10:13
  • 2
    You should provide a pointer to the definition of your `Signal`. It's impossible to know what it is. If I had to guess, a signal is a value depending on time (e.g. an oscillating signal), so we can't convert it to a single value. The best we could do is sampling the signal at a single point, but that's not interesting. In general there is no conversion between `F Int` and `Int`, for a generic `F`. E.g. we can not convert `[Int]` to `Int`, or `Maybe Int` to `Int`. – chi Nov 28 '18 at 10:21
  • @chi The library name _is_ given in the question, though of course it would be better to include a link. – Alexey Romanov Nov 28 '18 at 10:43
  • 1
    @AlexeyRomanov I only see "Lava" mentioned above, and there are [multiple packages](http://hackage.haskell.org/packages/search?terms=lava) for that, so I'm not sure. Perhaps it's [this one](http://hackage.haskell.org/package/kansas-lava-0.2.4.5/docs/Language-KansasLava-Signal.html). – chi Nov 28 '18 at 11:25

1 Answers1

1

Due to the way integer literals work in Haskell, your code is making comparisons x == fromInteger 0, x == fromInteger 1 etc. So it depends on the way == and fromInteger are implemented for Signal Int.

And if you check sources, it turns out fromInteger always creates a new Ref and won't be equal to any existing Signals.

So the question remains, how to do what you want. Pattern-matching should work, but instead of comparing with literals you'll need to go inside the actual structure of Signal. If I got it correct (without testing) something like this should work (returning Maybe Int because not all Signal Int signals are constant):

signalInt2int :: Signal Int -> Maybe Int
signalInt2int (Signal (Symbol ref)) = case deref ref of
    Int i -> Just i
    _ -> None
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487