How do I define a data type consisting of other data types?

后端 未结 2 1155
失恋的感觉
失恋的感觉 2021-01-14 20:50

I want to define the data type Currency, which consists of three other data types. I have the problem that Haskell doesn\'t recognize the data types as a part of currency, w

2条回答
  •  梦谈多话
    2021-01-14 21:27

    Currently your Currency is constructed as three values, that take no parameters. So Euro is a value, Dollar is a value, and Yen is a value, but not MkYen 15.

    You can add parameters to your data constructors like:

    data Currency = Euro Euro | Dollar Dollar | Yen Yen

    Then you thus can construct a Currency with:

    Euro (MkEuro 14 25) :: Currency

    The :: Currency is not necessary. The MkEuro will thus construct an object of the Euro type, and then we use the Euro data constructor with type Euro -> Currency to construct a Currency.

    Sadly I have to use the type Currency and can't create different functions for all three currencies.

    You might want to make a Currency typeclass however, that provides an interface that says what functions a currency should implement, and then make Euro, Dollar, and Yen instances of that typeclass.

提交回复
热议问题