Type-safe named fields in haskell ADTs -
there's mutual problem easy haskell. code-snippet describes this:
data jobdescription = jobone { n :: int } | jobtwo | jobthree { n :: int } deriving (show, eq) taskoneworker :: jobdescription -> io () taskoneworker t = putstrln $ "n: " ++ (show $ n t) main :: io () main = -- runs ok: taskoneworker (jobone 10) -- fails @ runtime: -- taskoneworker jobtwo -- works, didn't want to: -- taskoneworker (jobthree 10)
i described problem , it's possible solutions in article: https://www.fpcomplete.com/user/k_bx/playing-with-datakinds
here, on stackoverflow, i'd inquire -- best solutions problem, using tools , documentation?
i suggest using prism
. prism
_jobone
represents int
value lives within jobone
constructor. in taskoneworker
using ^?
. either value t
indeed jobone
constructor , argument homecoming in just
, or not jobone
constructor , nothing
.
{-# language templatehaskell #-} import control.lens info jobdescription = jobone { n :: int } | jobtwo | jobthree { n :: int } deriving (show, eq) $(makeprisms ''jobdescription) taskoneworker :: jobdescription -> io () taskoneworker t = case t ^? _jobone of n -> putstrln $ "n: " ++ show n nil -> putstrln "not jobone" -- or 'return ()' if want ignore these cases main :: io () main = taskoneworker (jobone 10) taskoneworker jobtwo taskoneworker (jobthree 10) -- *main> main -- n: 10 -- not jobone -- not jobone
haskell
No comments:
Post a Comment