Hi,

> How to implement heterogen lists in nim? In FP languages we've access to 
> better pattern matching and sum types but in nim I can't reproduce them 
> properly. I've tried it two different ways:

1\. this one fails because it can't infer the type of any(auto) - I need a 
third type parameter which should be optional:
    
    
    type
      HListKind = enum hkNil, hkCons
      HList*[H, T] = ref object of RootObj
        case kind*: HListKind
        of hkNil:
          isEmpty*: bool
        of hkCons:
          head*: H
          tail*: HList[T, any]
    
    let hNil*: HList[void, void] = HList[void, void](kind: hkNil, isEmpty: true)
    proc hList*[H, T](hd: H, tl: HList[T, any] = hNil): HList[H, T] =
      HList[H, T](hd, tl)
    
    
    Run

2\. this one doesn't fail but I don't know how to iterate over it:
    
    
    type
      HList*[H] = ref object of RootObj
        isEmpty*: bool
      HNil = ref object of HList[void]
      HCons*[H, T] = ref object of HList[H]
        head*: H
        tail*: HList[T]
    
    let hNil* = HNil(isEmpty: true)
    
    proc hList*[H](hd: H): HList[H] =
      HCons[H, void](head: hd, tail: hNil, isEmpty: false)
    
    proc hList*[H, T](hd: H, tl: HList[T]): HList[H] =
      HCons[H, T](head: hd, tail: tl, isEmpty: false)
    
    
    Run

Normally, I'd just use pattern matching but Nim doesn't support it so I'm stuck.

Reply via email to