【发布时间】:2012-12-29 21:14:01
【问题描述】:
我正在学习Jason Hickey's Introduction to Objective Caml。
有一个这样的练习:
练习 4.3 假设我们有一个基于以下替换密码的密码系统,其中每个明文都根据下表进行加密。
Plain | A B C D -------------------- Encrypted | C A D B例如,字符串
BAD将被加密为ACB。写一个函数
check,给定一个明文字符串s1和一个密文字符串s2,当且仅当 s2 是 s1 的密文时返回true。如果 s1 不是纯文本字符串,您的函数应该引发异常。您可能希望参考第 8 页上的字符串操作。随着字母变大,您的代码如何扩展? [强调添加]
基本上,我用might-be-stupid-naive 的方式编写了两个函数用于这个练习。
我想先就我的解决方案征求意见。
那么我想询问练习中突出显示的缩放解决方案的提示。
使用 if else
let check_cipher_1 s1 s2 =
let len1 = String.length s1 in
let len2 = String.length s2 in
if len1 = len2 then
let rec check pos =
if pos = -1 then
true
else
let sub1 = s1.[pos] in
let sub2 = s2.[pos] in
match sub1 with
| 'A' -> (match sub2 with
|'C' -> check (pos-1)
| _ -> false)
| 'B' -> (match sub2 with
|'A' -> check (pos-1)
| _ -> false)
| 'C' -> (match sub2 with
|'D' -> check (pos-1)
| _ -> false)
| 'D' -> (match sub2 with
|'B' -> check (pos-1)
| _ -> false)
| _ -> false;
in
check (len1-1)
else
false
到处使用纯匹配
let check_cipher_2 s1 s2 =
let len1 = String.length s1 in
let len2 = String.length s2 in
match () with
| () when len1 = len2 ->
let rec check pos =
match pos with
| -1 -> true
| _ ->
let sub1 = s1.[pos] in
let sub2 = s2.[pos] in
(*http://stackoverflow.com/questions/257605/ocaml-match-expression-inside-another-one*)
match sub1 with
| 'A' -> (match sub2 with
|'C' -> check (pos-1)
| _ -> false)
| 'B' -> (match sub2 with
|'A' -> check (pos-1)
| _ -> false)
| 'C' -> (match sub2 with
|'D' -> check (pos-1)
| _ -> false)
| 'D' -> (match sub2 with
|'B' -> check (pos-1)
| _ -> false)
| _ -> false
in
check (len1-1)
| () -> false
好的。上述两种方案类似。
我制作了这两个,因为这里http://www.quora.com/OCaml/What-is-the-syntax-for-nested-IF-statements-in-OCaml,有人说if else不是首选。
这基本上是我一生中第一次编写not-that-simple 函数。所以我真的很想在这里寻求建议。
例如,
- 如何改进这些解决方案?
- 我应该更喜欢
match而不是if else? - 我是否正确设计了
rec或use the rec? - 如果
in check (len1-1)正确?
缩放它
练习询问How does your code scale as the alphabet gets larger?。我现在真的没有头绪。在 Java 中,我会说我会有一个 map,然后对于 s1 中的每个字符,我正在寻找 s2 以获取相应的字符,并查看它是否是映射中的值。
对此有何建议?
【问题讨论】:
-
具体来说,使您的代码看起来很奇怪的主要问题是您在每个
let之后缩进。你绝对不想那样做。有关格式化 OCaml 的一些建议可以在 Caml Programming Guidelines 中找到——尤其是“如何缩进 let ... in 结构”一节。 -
@JeffreyScofield 这也是需要的。
标签: functional-programming ocaml