List 返回包含有效元素的列表
我想创建一个返回有效元素的函数List 返回包含有效元素的列表,list,ocaml,caml,List,Ocaml,Caml,我想创建一个返回有效元素的函数 (* 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
(* 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)]
;;
所以,我没有成功地做的是一个函数,它使用另外两个函数来返回一个正方形的邻域列表,但前提是它们在第格中
我尝试了List.fold_left,List.map,但每次它都说给定的类型不正确
(* 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)
;;
单元格类型如下所示:
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;;
更新 感谢Jeffrey Scofield,我找到了解决方案:
let is_valid_list m n c =
List.filter (function x -> is_valid m n x) (get_neighbours m n c)
;;
多亏了他。我认为,最初的问题是
List.map
是一个将每个输入转换为输出的函数。输入和输出列表的长度始终相同
在我看来,您似乎想要返回一个可能更小的列表。您要做的是过滤掉无效元素。List
模块中有一个名为List.filter
的函数可以执行此操作
其他问题可能是由于List.map
不可用造成的。但作为旁白,您对List.map
的调用是无效的OCaml。List.map
的参数是一个函数和一个列表。您正在传递一个参数,该参数在OCaml中看起来并不有效。它类似于函数定义的片段
List.filter
的参数包括:返回布尔值的函数(就像是有效的)和列表(就像您的列表a
)