gpt4 book ai didi

haskell - 自定义 ord 和 chr 函数

转载 作者:行者123 更新时间:2023-12-04 05:52:18 24 4
gpt4 key购买 nike

我需要编写“自定义” ord 和 chr 函数。我正在编写一个小程序来将凯撒密码应用于消息。执行此操作的最快方法是什么?

函数“ord”只需要取一个字符,然后返回适当的数字。 'A' 应该返回 0,'B' 应该返回 1,等等。假设我们只使用大写字母,所以我们只有 26 种可能性。我宁愿不写出 26 个守卫。有一个更好的方法吗?以下是它们的使用方法。 “chr”函数应该做相反的事情。

caesarencipher::Int->Int->String->String
caesarencipher r s p = map chr . map encipher $ plaintext
where
plaintext = map ord p
encipher p = mod (r*p + s) 26

caesardecipher::Int->Int->String->String
caesardecipher r s c = map chr . map decipher $ ciphertext
where
ciphertext = map ord c
inverser x | mod (r * x) 26 == 1 = x
| otherwise = inverser (x + 1)
decipher c = mod ((inverser 1) * (c - s)) 26

最佳答案

如果您真的想要以最快的方式定义这些函数的自定义版本,那么只需写出所有可能的模式。您可以通过用分号分隔多个子句来将它们打包到一行中。

不过,我看不出你会得到什么。 ordchr不会因为它们处理所有代码点而变慢; Char已经存储了一个完整的 Unicode 代码点。确实,ord应该基本免费,而且chr也是(除了简单的有效性检查之外)。那么为什么不将适当的数字偏移应用于标准 ordchr职能? (请注意,即使只是像我上面建议的那样写出模式也不会完全省略错误检查;如果传递的值没有任何子句处理,GHC 将抛出异常。)

关于haskell - 自定义 ord 和 chr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9936260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com