Search code examples
elmelm-signal

how to merge two signals with SampleOn in Elm


I try to merge two signals. One is Mouse.clicks and another is Keyboard.space.

  • On clicks, I should get a Signal(Int,Int) from Mouse.position as return value
  • On space, I should get something different so I can identify different signal is triggered.

My idea is:

type Event = Click | Space

mergedSignal : Signal Event
mergedSignal = 
  let
    clickSignal = map (\event -> Click) Mouse.clicks
    timeoutSignal = map (\event -> Space) Keyboard.space
  in
    merge clickSignal timeoutSignal

and get position somehow:

positionOnClickSignal:Signal (Int,Int)
positionOnClickSignal = sampleOn Mouse.clicks Mouse.position

Obviously, it is wrong.


Solution

  • It sounds like you want the mouse position to carry over as part of the event. In that case, you could redefine Event as

    type Event
      = Click (Int, Int)
      | Space
    

    Inside your mergedSignal, the clickSignal is currently just checking for Mouse.clicks but based on your description and other example, I think you actually want that to be based off positionOnclickSignal, which gives you a Signal (Int, Int), and using that, you can now populate the (Int, Int) portion of the Click (Int, Int) event like this:

    clickSignal =
      map Click positionOnClickSignal
    

    You'll notice that I took out the parenthesis in the above. That is more idiomatic for Elm, because Click is in essence a function that takes one (Int, Int) parameter, which will be passed in from the map function. It could have easily been written like this:

    clickSignal =
      map (\pos -> Click pos) positionOnClickSignal
    

    Now, if you're just trying to see some debug text of this on screen, a quick and easy way to go about that is to use show from the Graphics.Element package.

    import Graphics.Element exposing (show)
    
    main =
      map (show << toString) mergedSignal
    

    That will give you some debug text shown as the only thing on the page, and you could easily toss it up on http://elm-lang.org/try for testing.