Search code examples
ocamln-queens

Is there another, a bit shorter way to write this chunk of code down? (attack and attacked function)


Is there another way to write this code down in a shorter way? OCAML, not 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;;

Solution

  • abs exists in ocaml no need to reimplement it. attacked can be simplified as follow:

    let attacked listing =                                                          
      Array.map (fun i -> Array.exists (fun j -> i != j && attack i j) listing) listing