I'm working with lots of different time series data, and trying to make shortcuts for object initialisation, to write code like that:
echo OptionParams.init_seq @[
("call", 120.0, 1.2), ("call", 120.0, 1.3), ("call", 120.0, 1.5),
("call", 160.0, 1.2), ("call", 160.0, 1.3), ("call", 160.0, 1.5)
]
The problem is that T.init_seq function should accept tuples with arbitrary number of elements and translate it into the sequence of T.init calls.
I'm currently using a separate init_seq function for every number of elements (for 1, 2, 3 number of elements) could it be written in a better, general way, to work with any N number of elements?
import sequtils
template init_seq*[R, A](_: type[R], list: seq[A]): seq[R] =
list.map(proc (v: A): R = R.init(v))
template init_seq*[R, A, B](_: type[R], list: seq[(A, B)]): seq[R] =
list.map(proc (v: (A, B)): R = R.init(v[0], v[1]))
template init_seq*[R, A, B, C](_: type[R], list: seq[(A, B, C)]): seq[R] =
list.map(proc (v: (A, B, C)): R = R.init(v[0], v[1], v[2]))
type OptionParams* = tuple
right: string
tenor: float
moneyness: float
func init*(_: type[OptionParams], right: string, tenor: float, moneyness: float): OptionParams =
(right, tenor, moneyness)
echo OptionParams.init_seq @[
("call", 120.0, 1.2), ("call", 120.0, 1.3), ("call", 120.0, 1.5),
("call", 160.0, 1.2), ("call", 160.0, 1.3), ("call", 160.0, 1.5)
]
Template wont need strict concrete types https://play.nim-lang.org/#ix=2LsY
The most close to Duck Typing-ish that you can get on Nim.
Template wont need strict concrete types https://play.nim-lang.org/#ix=2LsY
Hmm, I still don't know how to use it to expand the tuple.
P.S.
But with the addition of untyped to_seq it helped me to make code below possible :)
template to_seq*(list: seq[untyped], R): seq[typeof R] = R.init_seq(list)
echo @[
("call", 120.0, 1.2), ("call", 120.0, 1.3), ("call", 120.0, 1.5),
("call", 160.0, 1.2), ("call", 160.0, 1.3), ("call", 160.0, 1.5)
].to_seq(OptionParams)