简体   繁体   中英

Defining Data Structures/ Types In Haskell

How would it possible to define a data structure in Haskell, such that there are certain constraints/rules that apply to the elements of the structure, AND be able to reflect this in the type.

For example, if I have a type made up of a list of another type, say

r = [x | x <- input, rule1, rule2, rule3].

In this case, the type of r is a list of elements of (type of x). But by saying this, we loose the rules. So how would it be possible to retain this extra information in the type definition.

To give more concreteness to my question, take the sudoko case. The grid of sudoko is a list of rows, which in turn is a list of cells. But as we all know, there are constraints on the values, frequency. But when one expresses the types, these constraints don't show up in the definition of the type of the grid and row.

Or is this not possible?

thanks.

In the example of a sodoku, create a data type that has multiple constructors, each representing a 'rule' or semantic property. IE

data SodokuType = NotValidatedRow | InvalidRow | ValidRow

Now in some validation function you would return an InvalidRow where you detect a validation of the sodoku rules, and a ValidRow where you detect a successful row (or column or square etc). This allows you to pattern match as well.

The problem you're having is that you're not using types, you're using values. You're defining a list of values, while the list does not say anything about the values it contains.

Note that the example I used is probably not very useful as it does not contain any information about the rows position or anything like that, but you can define it yourself as you'd like.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM