Haskell record syntax and type classes

后端 未结 4 1150
抹茶落季
抹茶落季 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:37

    You could use code such as

    data Foo = Foo { fooX :: Int, fooY :: Int } deriving (Show)
    data Bar = Bar { barX :: Int, barZ :: Int } deriving (Show)
    
    instance HasX Foo where
      getX = fooX
      setX r x' = r { fooX = x' }
    
    instance HasX Bar where
      getX = barX
      setX r x' = r { barX = x' }
    

    What are you modeling in your code? If we knew more about the problem, we could suggest something less awkward than this object-oriented design shoehorned into a functional language.

提交回复
热议问题