有没有另一种更短的方法来写下这段代码? (攻击和被攻击函数)
Is there another, a bit shorter way to write this chunk of code down? (attack and attacked function)
有没有其他方法可以用更短的方式写下这段代码?
OCAML,不是 Objective CAML。
let board = [|('a', 1); ('b', 2); ('c', 3); ('d', 4);('e', 5); ('f', 6);
('g', 7); ('h', 8)|];;
let int_of_col letter = int_of_char letter-96;;
let abs x = if x < 0 then - x else x;;
let attack (a,x)(b,y) = ((int_of_col a - int_of_col b)*(x-y))
= 0 || (abs(int_of_col a - int_of_col b) = abs(x-y));;
let attacked listing =
let out = Array.make 8 false in
for i=0 to 7 do
for j=0 to 7 do
if(i != j) then
if(attack listing.(i) listing.(j)) then out.(i) <- true
done
done;
out;;
abs
存在于 ocaml 中,无需重新实现它。 attacked
可以简化为:
let attacked listing =
Array.map (fun i -> Array.exists (fun j -> i != j && attack i j) listing) listing
有没有其他方法可以用更短的方式写下这段代码? OCAML,不是 Objective CAML。
let board = [|('a', 1); ('b', 2); ('c', 3); ('d', 4);('e', 5); ('f', 6);
('g', 7); ('h', 8)|];;
let int_of_col letter = int_of_char letter-96;;
let abs x = if x < 0 then - x else x;;
let attack (a,x)(b,y) = ((int_of_col a - int_of_col b)*(x-y))
= 0 || (abs(int_of_col a - int_of_col b) = abs(x-y));;
let attacked listing =
let out = Array.make 8 false in
for i=0 to 7 do
for j=0 to 7 do
if(i != j) then
if(attack listing.(i) listing.(j)) then out.(i) <- true
done
done;
out;;
abs
存在于 ocaml 中,无需重新实现它。 attacked
可以简化为:
let attacked listing =
Array.map (fun i -> Array.exists (fun j -> i != j && attack i j) listing) listing