scala - How to extract an element from an HList with a specific (parameterized) type -
i'm chaining transformations, , i'd accumulate result of each transformation can potentially used in subsequent step, , results available @ end (mostly debugging purposes). there several steps , time time need add new step or change inputs step.
hlist
seems offer convenient way collect results in flexible still type-safe way. i'd rather not complicate actual steps making them deal hlist , accompanying business.
here's simplified version of combinator i'd write, isn't working. idea given hlist containing a, , index of a, , function -> b, mapnth
extract a, run function, , cons result onto list. resulting extended list captures type of new result, several of these mapnth-ified steps can composed produce list containing result each step:
def mapnth[l <: hlist, a, b] (l: l, index: nat, f: => b) (implicit at: shapeless.ops.hlist.at[l, index.n]): b :: l = f(l(index)) :: l
incidentally, i'll need map2nth
taking 2 indices , f: (a, b) => c
, believe issues same.
however, mapnth
not compile, saying l(index)
has type at.out
, f
's argument should a
. that's correct, of course, suppose need way provide evidence at.out
in fact a
(or, at.out <: a
).
is there way express constraint? believe have take form of implicit, because of course constraint can checked when mapnth
applied particular list , function.
you're right needing evidence at.out
a
, , can provide evidence including value of type member in at
's type:
def mapnth[l <: hlist, a, b] (l: l, index: nat, f: => b) (implicit at: shapeless.ops.hlist.at[l, index.n] { type out = }): b :: l = f(l(index)) :: l
the companion objects type classes at
in shapeless define aux
type includes output type final type parameter.
def mapnth[l <: hlist, a, b] (l: l, index: nat, f: => b) (implicit at: shapeless.ops.hlist.at.aux[l, index.n, a]): b :: l = f(l(index)) :: l
this pretty equivalent more idiomatic (and looks little nicer).
Comments
Post a Comment