Using Haskell's types to replace assert statements or if checks in other languages

后端 未结 3 1946
执笔经年
执笔经年 2021-02-19 15:07

Sorry if the question is very elementary, I am still very new to Haskell. Lets say I have a function that can only work with two numbers that are in the golden ration (1.618), h

3条回答
  •  没有蜡笔的小新
    2021-02-19 15:38

    The easiest technique is to use smart constructors, which use a function from Int to GoldenInt, that checks that your values are in the required ratios.

    With more effort, you can use type level numbers to ensure that no runtime check is necessary, however, given you're a beginner, I would stick to the smart constructor method.

    Tom's answer above is an example of this idiom.

提交回复
热议问题