问题
I'm trying to shift array by k
to left.
Here's my code. But I'm getting compile error on shifted;;
line.
let shift_left (arr: array) (kk: int) =
let size = Array.length arr in
let k = kk mod size in
let shifted = Array.make size 0 in
for i = 0 to size - 1 do
if i < k
then (shifted.(size - k + i) <- arr.(i))
else (shifted.(i-k) <- arr.(i))
done
shifted;;
let arr = [| 1; 2; 3; 4; 5; 6; 7; 8; 9; 10 |];;
let shifted = shift arr 4;;
Array.iter print_int arr;
print_string "\n";;
Array.iter print_int shifted;
print_string "\n";;
Here is what I getting in terminal:
$ ocamlc -o shift shift.ml
File "shift.ml", line 11, characters 1-8:
Error: Syntax error
回答1:
There are two compiler errors here:
A syntax error between
done
andshifted
. Because line breaks are not significant in OCaml, it will be parsed asdone shifted;;
, which looks like a function application, but is not valid sincedone
is a keyword, not an identifier that might refer to a function. Use the sequence operator,;
, to evaluate two expressions in sequence.A type error:
array
is not a concrete type, it takes a type parameter specifying the type of value it contains. It should beint array
in this case.
来源:https://stackoverflow.com/questions/57152344/syntax-error-in-function-to-shift-array-by-k