将数字限制在一个范围内(Haskell)

编程入门 行业动态 更新时间:2024-10-12 01:26:51
本文介绍了将数字限制在一个范围内(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)

本文发布于:2023-11-07 19:26:19,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:范围内   数字   Haskell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!