Guest User

Untitled

a guest
Jun 17th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. /**
  2. * N-tuples -- type safe and compile-time checked tuples that can be composed up to an arbitrary size.
  3. *
  4. * Sometimes referred to a HLists from the Haskell library by that name. HList is short for heterogeneous list, which accurately
  5. * reflects their structure in the type system: a singly linked list composed of cons cells and a terminating Nil. However, from
  6. * a usage perspective they more closely resemble tuples.
  7. */
  8. object NTuples {
  9. /** The supertype of NTuples of any size */
  10. sealed trait NTuple {
  11. /** Convert an NTuple to an erased list */
  12. def toList: List[Any]
  13. }
  14.  
  15. /** The "Nil" for NTuples, must be at the end of an NTuple to signal the termination of the list */
  16. final class NTupleEnd private[NTuples] () extends NTuple {
  17. /** Produce a new NTuple with the given element as the sole one */
  18. def :+: [A] (lhs: A): A :+: NTupleEnd = NTupleElement(lhs, this)
  19.  
  20. def toList = Nil
  21. }
  22.  
  23. /** The singleton NTupleEnd. Done this way rather than using objects because of Scala's strange handling of object types */
  24. val NTupleEnd = new NTupleEnd
  25.  
  26. /** Cons cell of NTuples, with one element and the rest of the NTuple */
  27. final case class NTupleElement[B, C <: NTuple](head: B, tail: C) extends NTuple {
  28. /** Produce a new NTuple with the given element prepended to this NTuple */
  29. def :+: [A] (lhs: A): A :+: B :+: C = NTupleElement(lhs, this)
  30. def toList = head :: tail.toList
  31. }
  32.  
  33. /** Type alias for NTupleElement which makes typing naming and construction more succint */
  34. type :+: [Head, Tail <: NTuple] = NTupleElement[Head, Tail]
  35.  
  36. /** Extractor object so that NTuples can be matched */
  37. object :+: {
  38. def unapply[A, B <: NTuple](in: NTupleElement[A, B]): Option[(A, B)] = Some(in.head, in.tail)
  39. }
  40. }
Add Comment
Please, Sign In to add comment