如何限制一个Int域的值范围? [英] How to limit a Int field to a range of values?

查看:108
本文介绍了如何限制一个Int域的值范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据

  data User = User {uRank :: Int,uProgress :: Int} 

我想将 uRank 限制为值列表[-1 ,1,3],例如。

我该如何做?

解决方案 div>

定义一个小和类型是这个特定问题的最佳答案。你也可以用 newtype 和智能构造函数来达到这个效果。

  newtype排名= UnsafeMkRank {unRank :: Int} 

mkRank :: Int - >也许Rank
mkRank i
|我`elem` [-1,1,3] = Just(UnsafeMkRank i)
|否则= Nothing

现在,只要您使用安全 mkRank 构造函数,你可以假设你的 Rank 值有你想要的 Int 值。


In my Data

data User = User { uRank :: Int, uProgress :: Int }

I want to limit uRank to a list of values [-1, 1, 3], for example.

How do I do this?

解决方案

Defining a small sum type is the best answer for this specific question. You can also use newtype with smart constructors to achieve this effect.

newtype Rank = UnsafeMkRank { unRank :: Int }

mkRank :: Int -> Maybe Rank
mkRank i 
    | i `elem` [-1, 1, 3] = Just (UnsafeMkRank i)
    | otherwise = Nothing

Now, provided you only use the safe mkRank constructor, you can assume that your Rank values have the Int values you want.

这篇关于如何限制一个Int域的值范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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