SML如何在char列表上返回int?
我有点难以弄清楚如何将每个处理后的字符恢复为 int 值。
该函数应该像这样工作: val caesar = fn : int * int -> int
所以如果 k = 2466 且 n = 2,那么输出应该是 4688
希望代码不会太奇怪(我是 SML 新手)。
(* Load Libs *)
load "Int";
load "Real";
load "String";
load "Char";
load "List";
fun caesar (k, n) =
let
fun k_string (i) = Int.toString(i)
fun item_k_char (x, y) = Char.ord (List.nth (x, y))
val val_k_string = k_string(k)
val k_explode = String.explode(val_k_string)
val counter = ref 0
val counter_end = (String.size(val_k_string) - 1)
in
while (!counter >= counter_end) do (
item_k_char(k_explode, !counter) + n;
counter := !counter + 1
)
end;
I'm having a bit difficulty figuring out, how to get each of the processed chars back to an int value.
The function should work like: val caesar = fn : int * int -> int
So if k = 2466 and n = 2, then the output should be 4688
Hope the code isn't too weird (I'm a SML newbie).
(* Load Libs *)
load "Int";
load "Real";
load "String";
load "Char";
load "List";
fun caesar (k, n) =
let
fun k_string (i) = Int.toString(i)
fun item_k_char (x, y) = Char.ord (List.nth (x, y))
val val_k_string = k_string(k)
val k_explode = String.explode(val_k_string)
val counter = ref 0
val counter_end = (String.size(val_k_string) - 1)
in
while (!counter >= counter_end) do (
item_k_char(k_explode, !counter) + n;
counter := !counter + 1
)
end;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
while 循环并不是最好的工具。相反,您可以使用
map
它为给定列表中的每个项目执行给定函数,并返回一个包含每次调用该函数的结果的新列表。换句话说:
map (fn c => (Char.ord c) + 2) [#"2", #"4", #"6", #"6"]
将返回[52,54,56,56]
。您可以将其转换回 char 并使用 String.implode 来获取字符串“4688”。您可能还想添加一些逻辑,使数字“环绕”,即
caesar (7,7)
变为4
。所以总而言之你的代码变成:
A while loop isn't the best tool here. Instead you can use
map
which executes a given function for each item in a given list and returns a new list containing the result of each call to the function.In other words:
map (fn c => (Char.ord c) + 2) [#"2", #"4", #"6", #"6"]
will return[52,54,56,56]
. You can the convert this back to char and useString.implode
to get the string "4688".You probably also want to add some logic so that the numbers "wrap around", i.e.
caesar (7,7)
becomes4
.So all in all your code becomes: