将数字限制在一个范围内(Haskell) [英] Limit a number to a range (Haskell)

查看:124
本文介绍了将数字限制在一个范围内(Haskell)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在公开一个带有两个参数的函数,一个是最小边界,另一个是最大边界。我如何确保使用类型,例如最小边界不大于最大边界?



我想避免创建一个智能构造函数并返回Maybe,因为它会使整个使用更加繁琐。



谢谢 解决方案

这并不能完全回答你的问题,但有时候有效的方法之一是改变你的类型的解释。例如,而不是

  data Range = {lo :: Integer,hi :: Integer} 

您可以使用

 数据范围= {lo :: Integer,size :: Natural} 

这样,就无法表示无效的范围。


I am exposing a function which takes two parameters, one is a minimum bound and the other is a maximum bound. How can I ensure, using types, that for example the minimum bound is not greater than the maximum bound?

I want to avoid creating a smart constructor and returning a Maybe because it would make the whole usage more cumbersome.

Thank you

解决方案

This doesn't exactly answer your question, but one approach that sometimes works is to change your interpretation of your type. For example, instead of

data Range = {lo :: Integer, hi :: Integer}

you could use

data Range = {lo :: Integer, size :: Natural}

This way, there's no way to represent an invalid range.

这篇关于将数字限制在一个范围内(Haskell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆