Haskell type of specific data constructor -
suppose have following haskell code:
data option = | opt1 int double string -- more options here in real case handleoption :: option -> io () handleoption option = case option of -> handlehelp opt1 n f s -> handleopt1 n f s handlehelp :: io () handlehelp = print "help" handleopt1 :: int -> double -> string -> io () handleopt1 n f s = print (n, f, s)
in above code, seems me waste deconstruct object ahead of time in sense keep data bundled neatly together. have pass each part of opt1 individually or create single separate data type haul them along. possible pass in entire opt1
handleopt1
while not allowing general option
instance being passed in, such making handleopt1 help
compile error?
example pseudo code below:
data option = | opt1 int double string handleoption :: option -> io () handleoption option = case option of -> handlehelp opt1 @ opt1{} -> handleopt1 opt1 handlehelp :: io () handlehelp = print "help" handleopt1 :: option:opt1 -> io () handleopt1 (opt1 n f s) = print (n, f, s)
you can use gadts this.
{-# language gadts #-} data option :: option () opt1 :: int -> double -> string -> option (int, double, string) handleoption :: option -> io () handleoption option = case option of -> handlehelp opt1 @ opt1{} -> handleopt1 opt1 handlehelp :: io () handlehelp = print "help" handleopt1 :: option (int, double, string) -> io () handleopt1 (opt1 n f s) = print (n, f, s)
with gadts, give more type information compiler. handleopt1
, since accepts option (int, double, string)
, compiler knows option ()
(i.e. help
) never passed in.
that said, using gadts makes quite few other things harder. instance, automatic deriving (e.g. deriving (eq, show)
) doesn't work them. should consider pros , cons of using them in case.
Comments
Post a Comment