How do I define a data type that only accepts numbers?

后端 未结 3 1064
抹茶落季
抹茶落季 2020-12-30 05:34

I am attempting to create a data type, Point, that takes three numbers for its constructor. Initially, I had written

data Point = Point Double D         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 06:07

    You can use the Num typeclass to enforce Num constraint on your datatype. The usual syntax would be something like:

    data MyTypeClass a => MyDataType a = MyDataTypeConstructor1 a|MyDataTypeConstructor2 a a|{- and so on... -}
    

    In your case, you can do

    data Num a => Point a = Point a a a 
    

    Read more about data type specifications and LYAH. Real World Haskell also mentions this.

    EDIT

    As mentioned by shachaf, this is not quite valid haskell2010, though the specification mentions it. I should also note that this form is seldom used and the preferred way to enforce these constraints through functions than through typeclasses/datatypes, since they introduce an additional dependency on types.

提交回复
热议问题