Search code examples
listscaladictionaryshapelessheterogeneous

Dynamically growing heterogeneous list, Scala


Is there a way to persist(I mean keep in a var) (is it possible?) a dynamically growing HList ? my pseudo code:

var llist = 1 :: 2 :: "foo" :: true :: HNil
var list: HList = HNil // here is a wrong type! in fact we dont need HList type

object mapFunc extends Poly1 {
    implicit def default[T] = at[T](t => { list = t :: list })
}

llist map mapFunc

Obviously, this code doesnt work. so ofc it works, but we cant even do list.head by reason of incorrect HList typing (as i recognize, list even doesnt keep type parameter at all).

The result type:

shapeless.HList = true :: foo :: 2 :: 1 :: HNil

so, that's incorrect.

EDIT

the information above is not enough, i see.

So i wanted to have in some object, smth like a variable, which can be of any HList type;

class className {
    var hlist: HList = _ // it is not correct
}

in order to pass sometimes HList in this variable;

className.hlist = llist

p.s. @milessabin mb right that its better to find another solution to my problem.


Solution

  • It's not really clear to me exactly what you're trying to achieve here. By and large you should try and think in terms of functional folds and unfolds rather than mutable updates.

    A solution to the specific problem you've shown in your question is just,

    scala> val llist = 1 :: 2 :: "foo" :: true :: HNil
    llist: Int :: Int :: String :: Boolean :: HNil = 1 :: 2 :: foo :: true :: HNil
    
    scala> llist.reverse
    res0: Boolean :: String :: Int :: Int :: HNil = true :: foo :: 2 :: 1 :: HNil
    

    The reverse method on HList is implemented as a fold (at both the type and value levels), and can be found here.