listocamlcaml

Return list with valid elements


I would like to create a function that return valid elements.

(* Return true if the square given (c) is in the grid (m*n) *)
let is_valid m n c =
  List.mem c (range2 m n)
;;

(* Return the list of the neighbours of a square in a grid(m*c) *)
let get_neighbours m n c =
  let (x,y) = c in [(x-1,y);(x,y+1);(x+1,y);(x,y-1)]
;;

So what I don't succeed to do is a function that use the two others in order to return a list of the neighbours of a square but only if they are in th grid.

I tried with List.fold_left, List.map but every time it said that the given type is incorrect.

(* this is what i tried to make*)

let verif m n c = 
  let a = (get_neighbours m n c) in
  List.map (a -> is_valid m n a) 
;;

Type Cell is given like so:

module Cell =
struct
  type t = int * int
  let compare = Pervasives.compare
end
;;

module CellMap = Map.Make(Cell);;
module CellSet = Set.Make(Cell);;
type grid = CellSet.t CellMap.t;;

UPDATE

Thanks to Jeffrey Scofield I found the solution:

let is_valid_list m n c =
  List.filter (function x -> is_valid m n x) (get_neighbours m n c)
;;

Thanks to him.


Solution

  • The initial problem, I think, is that List.map is a function that transforms each of its inputs into an output. The input and output lists are always the same length.

    It seems to me you want to return a potentially smaller list. What you want to do is to filter out the invalid elements. There is a function in the List module named List.filter that does this.

    Your other problems may be caused by the fact that List.map isn't usable. But just as a side comment, your call to List.map is not valid OCaml. The parameters to List.map are a function and a list. You are passing one parameter that doesn't look like anything valid in OCaml. It resembles a fragment of a function definition.

    The parameters to List.filter are: a function returning a boolean (just like is_valid) and a list (like your list a).