Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm function with the type: Signal (List a) -> List (Signal a)

I am new to elm and functional programming in general. But I am using elm and I really need a function that has a Signal (List String) as an input and returns List (Signal String).

I know I probably shouldn't have this problem with a better architectural design in my program but having a function that could do this would solve a big problem for me.

The combine function does exactly the opposite:

combine : List (Signal a) -> Signal (List a)
combine = List.foldr (map2 (::)) (constant [])

I've tried to do something similar to the combine function but have been unsuccessful so far. Any ideas on how to create such function?

like image 863
Snorri Hannesson Avatar asked Apr 22 '15 17:04

Snorri Hannesson


1 Answers

This is not possible in general

The inverse of combine is not (in general) possible.
When you have a list of static size of signals, then you can combine them into a signal of lists of static size. But when you go the other way, there is no guarantee that the lists in the signal are a static size. Therefore you cannot "just" construct a list out of it.
(If you could then a normal value of type List could have a changing size without showing Signal around the type, and you would be dynamically creating and destroying signals in the list. Those are two things Elm disallows. )

But with some restrictions...

Of course if you know that the list in the signal is of a static size, you can write a specific function based on that assumption; that function would then fail at runtime if the case occurs that your assumption of static size lists was wrong.

unsafe : Maybe a -> a
unsafeHead m =
  case m of
    Just a -> a
    Nothing -> Debug.crash "unsafe: You're out of luck. The `Maybe` was not a `Just`. "

uncombine : Int -> Signal (List a) -> List (Signal a)
uncombine n sig =
  if n == 0
    then []
    else Signal.map (List.head >> unsafe) sig
      :: uncombine (n-1) (Signal.map (List.tail >> unsafe) sig)

(I'm quite sure this question was discussed on the elm-discuss mailing list once, but I can't find it any more)

like image 83
Apanatshka Avatar answered Oct 16 '22 00:10

Apanatshka