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 caesa开发者_运维百科r (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;
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 use String.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)
becomes 4
.
So all in all your code becomes:
fun caesar (k, n) =
let
val val_k_string = Int.toString k
val k_explode = String.explode val_k_string
val ints = map (fn c => (Char.ord c) + n) k_explode
val wrappedAroundInts = map (fn i => (i - 48) mod 10 + 48) ints
val chars = map Char.chr wrappedAroundInts
val string = String.implode chars
in
Option.valOf (Int.fromString string)
end
精彩评论