在 OCaml 中将列表 [1,2,3] 推进到 [3,1,2]
Advance a list [1,2,3] to [3,1,2] in OCaml
我正在尝试编写一个简单的 OCaml 程序来推进向量,即 [1,2,3] 转到 [3,1,2] 等等:
open Printf
let advance_list list =
match list with
|[] -> []
|h::t -> t::h
let () = List.iter (printf "%d ") (advance_list [1;2;3])
但我明白了
File "rotate_vector.ml", line 13, characters 16-17:
13 | |h::t -> t::h
^
Error: This expression has type 'a but an expression was expected of type
'a list list
The type variable 'a occurs inside 'a list list
我不明白这个错误。对我来说,我返回附加到 h
开头的第一个元素,这是没有第一个元素 t
的列表
列表的头部和尾部不是同一类型。对于t list
类型的列表,列表的头部是t
类型,但列表的尾部是t list
类型。也就是说,列表的尾部也是一个列表。
因此,您不能使用 ::
运算符来切换它们。您需要在左侧使用 t
类型的内容,在右侧使用 t list
类型的内容。
无论如何,您需要在末尾而不是开头拆分列表。为此,您需要一些更复杂的东西。我可以想象一个遍历列表的函数,跟踪到目前为止看到的内容(列表的开头),然后在到达结尾时将结果放在一起。
let get_last_elt l =
let list_rev = List.rev l in
match list_rev with
[] -> failwith "The list is empty"
|h::t -> let end_of_list = h in end_of_list
let delete_last_elt l =
let list_rev = List.rev l in
match list_rev with
[] -> failwith "The list is empty"
|h::t -> List.rev t
let advance_list l =
let end_of_list = get_last_elt l in
match l with
[] -> failwith "The list is empty"
|h::t -> [end_of_list]@(delete_last_elt l)
希望对您有所帮助!
我正在尝试编写一个简单的 OCaml 程序来推进向量,即 [1,2,3] 转到 [3,1,2] 等等:
open Printf
let advance_list list =
match list with
|[] -> []
|h::t -> t::h
let () = List.iter (printf "%d ") (advance_list [1;2;3])
但我明白了
File "rotate_vector.ml", line 13, characters 16-17:
13 | |h::t -> t::h
^
Error: This expression has type 'a but an expression was expected of type
'a list list
The type variable 'a occurs inside 'a list list
我不明白这个错误。对我来说,我返回附加到 h
开头的第一个元素,这是没有第一个元素 t
列表的头部和尾部不是同一类型。对于t list
类型的列表,列表的头部是t
类型,但列表的尾部是t list
类型。也就是说,列表的尾部也是一个列表。
因此,您不能使用 ::
运算符来切换它们。您需要在左侧使用 t
类型的内容,在右侧使用 t list
类型的内容。
无论如何,您需要在末尾而不是开头拆分列表。为此,您需要一些更复杂的东西。我可以想象一个遍历列表的函数,跟踪到目前为止看到的内容(列表的开头),然后在到达结尾时将结果放在一起。
let get_last_elt l =
let list_rev = List.rev l in
match list_rev with
[] -> failwith "The list is empty"
|h::t -> let end_of_list = h in end_of_list
let delete_last_elt l =
let list_rev = List.rev l in
match list_rev with
[] -> failwith "The list is empty"
|h::t -> List.rev t
let advance_list l =
let end_of_list = get_last_elt l in
match l with
[] -> failwith "The list is empty"
|h::t -> [end_of_list]@(delete_last_elt l)
希望对您有所帮助!