Haskell record syntax and type classes

后端 未结 4 1160
抹茶落季
抹茶落季 2020-12-17 14:57

Suppose that I have two data types Foo and Bar. Foo has fields x and y. Bar has fields x and z. I want to be able to write a function that takes either a Foo or a Bar as

4条回答
  •  情深已故
    2020-12-17 15:32

    Seems to me like a job for generics. If you could tag your Int with different newtypes, then you would be able to write (with uniplate, module PlateData):

    data Foo = Foo Something Another deriving (Data,Typeable)
    data Bar = Bar Another Thing deriving (Data, Typerable)
    
    data Opts = F Foo | B Bar
    
    newtype Something = S Int
    newtype Another = A Int
    newtype Thing = T Int
    
    getAnothers opts = [ x | A x <- universeBi opts ]
    

    This would extract all Another's from anywhere inside the Opts.

    Modification is possible as well.

提交回复
热议问题