1

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.

DaunnC
  • 1,301
  • 15
  • 30
  • Can you clarify what you mean by persist? I thought perhaps you meant into a DB. I'm not sure if you want an HList of HLists or what the end product/goal should be. – wheaties Oct 14 '13 at 13:30
  • ok, thx, I've edited; btw, I mean dynamically to add elements to a variable with some `HList`, for example add some element to existing list (for example empty)... but it seems to me it's impossible, cause we can't redefine variable type. In case of simple lists we can achieve this, cause of sub typing and in fact we loose information about the type. So, thank u! Is it possible to remove question 'cause mb it is not useful, and the most possible answer is 'no'? – DaunnC Oct 14 '13 at 14:59
  • dynamically growing an HList is the standard usecase. They've got append and all that built right in. – wheaties Oct 14 '13 at 15:36
  • It might be helpful if you showed the code that you'd like to be able to write. – Miles Sabin Oct 14 '13 at 15:38

1 Answers1

3

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.

Miles Sabin
  • 23,015
  • 6
  • 61
  • 95