Return 包含有效元素的列表
Return list with valid elements
我想创建一个 return 有效元素的函数。
(* 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)]
;;
所以我没有成功做的是一个函数,它使用另外两个函数来 return 一个正方形的邻居列表,但前提是它们在网格中。
我试过 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
是一个将其每个输入转换为输出的函数。输入和输出列表的长度始终相同。
在我看来,您想要 return 一个可能更小的列表。您要做的是过滤掉无效元素。 List
模块中有一个名为 List.filter
的函数可以执行此操作。
您的其他问题可能是由于 List.map
不可用造成的。但作为旁注,您对 List.map
的调用是无效的 OCaml。 List.map
的参数是一个函数和一个列表。您正在传递一个在 OCaml 中看起来无效的参数。它类似于函数定义的片段。
List.filter
的参数是:一个函数 return 一个布尔值(就像 is_valid
)和一个列表(就像你的列表 a
)。
我想创建一个 return 有效元素的函数。
(* 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)]
;;
所以我没有成功做的是一个函数,它使用另外两个函数来 return 一个正方形的邻居列表,但前提是它们在网格中。
我试过 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
是一个将其每个输入转换为输出的函数。输入和输出列表的长度始终相同。
在我看来,您想要 return 一个可能更小的列表。您要做的是过滤掉无效元素。 List
模块中有一个名为 List.filter
的函数可以执行此操作。
您的其他问题可能是由于 List.map
不可用造成的。但作为旁注,您对 List.map
的调用是无效的 OCaml。 List.map
的参数是一个函数和一个列表。您正在传递一个在 OCaml 中看起来无效的参数。它类似于函数定义的片段。
List.filter
的参数是:一个函数 return 一个布尔值(就像 is_valid
)和一个列表(就像你的列表 a
)。