Is it possible to type a variadic function in Haskell? -
mind following haskell term:
callntimes :: forall . int -> (a -> a) -> -> callntimes n f 0 = x callntimes n f x = f (callntimes (n-1) f x) firstof :: ?????? firstof n = callntimes n (\ x y -> x)
if ignore types , normalize functions hand, firstof
function receives n
, n
arguments, discards first , returns it. firstof 3 10 20 30
returns 3
. possible type function in ghc 8.0 new dependent typing features?
i managed working version - it's not asked demonstrates commenting , think it's quite close
{-# language flexiblecontexts #-} {-# language typefamilies #-} {-# language multiparamtypeclasses #-} module variadic data z = z data s t = s (t a) class var n type el n :: * type res n :: * firstof :: n -> el n -> res n instance var (z a) type el (z a) = type res (z a) = firstof z = instance (el (n a) ~ a, var (n a)) => var (s n a) type el (s n a) = type res (s n a) = -> res (n a) firstof (s n) _ = firstof n
here few examples:
λ> firstof z 5 5 λ> firstof (s z) 5 9 5 λ> firstof (s (s z)) 5 8 9 5 λ> firstof (s (s z)) "hi" "world" "uhu" "hi"
if interested in how got there can check edit-history
remarks
- it uses
s
,z
poor-mansreplacement* type-level literals , can working this - the version
firstof (s (s z))
expect want 2 arguments waiting 3 - that's because startz
= 1 argument - i saw wanted
firstof 3 10 20 30 = 3
not (this give10
) - doable type-level literals , obvious overload too
Comments
Post a Comment