如何在 haskell 中使用常量以避免幻数?

发布于 2024-09-07 04:04:05 字数 55 浏览 4 评论 0原文

假设我有一个从 1 到 MAGIC_NUMBER 的数字列表 - 有没有办法可以提前声明这一点?

Say I have a list of numbers from 1 to MAGIC_NUMBER -- Is there a way I can declare this beforehand ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

很糊涂小朋友 2024-09-14 04:04:05

当然。事实上,鉴于 Haskell 是纯函数式的,定义常量比定义非常量要容易得多。

magicNumber = 42

magicList = [1..magicNumber]

Sure. In fact, given that Haskell is purely functional, it's much easier to define a constant than a non-constant.

magicNumber = 42

magicList = [1..magicNumber]
弄潮 2024-09-14 04:04:05

Chuck和Ony的答案是正确的。您应该注意一个陷阱:

magicNum = 42

f magicNum = 'A'
f _ = 'B'

这不是您所期望的 - 第二行中的 magicNum 是一种匹配所有内容的模式,就像 fx = 'A' 一样。使用 fx | x == magicNum = 'A'。

Chuck's and ony's answers are correct. There's one trap you should be aware of:

magicNum = 42

f magicNum = 'A'
f _ = 'B'

is NOT what you might expect - magicNum in second line is a pattern that matches everything, just like f x = 'A'. Use f x | x == magicNum = 'A'.

紧拥背影 2024-09-14 04:04:05

您可以在所有计算中使用代数数据,并使用一些命名值(如果它们确实“神奇”),或者将代数值构建为“神奇”数字等等:

class FlagsMask f where mask :: f -> Int

data Magics = Alpha | Beta | Gamma
    deriving (Enum, Read, Show, Eq, Ord)

instance FlagsMask Magics where
    mask m = 2 ^ fromEnum m

data PermsFlag = FlagRead | FlagWrite | FlagExec | FlagSuper

-- [flagRead, flagWrite, flagExec] = [2^n | n <- [0..2]]
(flagRead : flagWrite : flagExec : _) = [2^n | n <- [0..]]
flagSuper = 16

instance FlagsMask PermsFlag  where
    mask FlagRead = flagRead
    mask FlagWrite = flagWrite
    mask FlagExec = flagExec
    mask FlagSuper = flagSuper
*Main> map fromEnum [Alpha .. ]
[0,1,2]
it :: [Int]
*Main> zip [Alpha .. ] [1..]
[(Alpha,1),(Beta,2),(Gamma,3)]
it :: [(Magics, Integer)]

You can use algebraic data in all your calculations and use some named values if they are really "magic", or build render of algebraic values to "magic" numbers and many more:

class FlagsMask f where mask :: f -> Int

data Magics = Alpha | Beta | Gamma
    deriving (Enum, Read, Show, Eq, Ord)

instance FlagsMask Magics where
    mask m = 2 ^ fromEnum m

data PermsFlag = FlagRead | FlagWrite | FlagExec | FlagSuper

-- [flagRead, flagWrite, flagExec] = [2^n | n <- [0..2]]
(flagRead : flagWrite : flagExec : _) = [2^n | n <- [0..]]
flagSuper = 16

instance FlagsMask PermsFlag  where
    mask FlagRead = flagRead
    mask FlagWrite = flagWrite
    mask FlagExec = flagExec
    mask FlagSuper = flagSuper
*Main> map fromEnum [Alpha .. ]
[0,1,2]
it :: [Int]
*Main> zip [Alpha .. ] [1..]
[(Alpha,1),(Beta,2),(Gamma,3)]
it :: [(Magics, Integer)]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文