1

i want to combine multiple options to an option of a tuple:

val maybeA: Option[Int] = ...
val maybeB: Option[String] = ...

val combined: Option[(Int,String)] = combine(maybeA, maybeB)

there are many ways to do this, let's go with:

def combined[X,Y](maybeA: Option[X], maybeB: Option[Y]) = maybeA.zip(maybeB).headOption

and that's great.

now i wonder, can this be done for varargs and a tuple dynamically somehow? what would the signature look like?

def combine[???](options: Option[?]*): Tuple[?]
nathan g
  • 858
  • 9
  • 17
  • this is just theoretically, out of idle curiosity and understanding the limits of the language – nathan g Jan 28 '20 at 10:43
  • 1
    Completely dynamic is impossible. Because what is the input type and what is the output type? However, you may implement it as some kind of **macro** which will infer the correct output type, but that would require that all the values are knew in each use site _(so you can't pass a dynamic list of values)_. However, you will find that the macro is very hard to implement, and that you probably will never need more than x options, so it may be easier to just write each method from 2 options until x options, which will be tedious, but is easily automatable on a code generator script. – Luis Miguel Mejía Suárez Jan 28 '20 at 12:03
  • Anyways, if you just need the implementation rather than doing yourself, this is basically what `tupled` will do for any _Applicative_. So, you may just use **cats** and write: `(o1, o2, ..., on).tupled` and it will return an option of tuple of the values. – Luis Miguel Mejía Suárez Jan 28 '20 at 12:05
  • @LuisMiguelMejíaSuárez the reason i wanted to implement it myself (as an exercise) is because i wanted the options to be evaluated lazily. the input type is then: => Option[?]*, the options are defined with lazy val and the combiner should not evaluate options unnecessarily once a None is encountered. i will read up on tupled and Applicative, what i know about tupled is that it's a way to change the input params of a function to a tuple, which isn't exactly what i had in mind, but i'll think about it some more – nathan g Jan 28 '20 at 12:30
  • 1
    Then, I would go with the source generator to generate all the overloads from 2 to n options. – Luis Miguel Mejía Suárez Jan 28 '20 at 12:37
  • any computer language experts are welcome to leave a comment elaborating on theoretical concepts/abilities missing from the language that would have made this possible – nathan g Jan 28 '20 at 14:01
  • If you could append elements to a tuple, it would be trivial. Looks like there is a way to do it. Maybe this helps: https://stackoverflow.com/q/15349439/302793 – lex82 Jan 28 '20 at 19:02

0 Answers0