Ocaml:必要时展平列表
Ocaml : flatten a list if necessary
我从 ocaml 开始,我想知道如何在类型的递归函数中
'一个列表 -> int ,
let rec int l =
match l with
| [] -> 0
| hd::tl -> 10
仅在必要时才可以展平列表
例如,如果 [0;2;3;4] 只是 return 的整数
如果 [[0];2; [3;4]],然后执行 -> [0;2;3;4] 然后 return int.
提前致谢。
您不能直接存储列表或列表中的数字,因为列表必须存储相同类型的值。
但是,您可以为这两种值声明一个变体类型(标记联合)。
这里的类型 'a lisr_or_val
表示的值要么是类型 'a
的值,例如表示为 (A 3)
,要么是类型 'a lisr_or_val
的值列表,例如示例 (L [(A 3); (A 5)])
:
type 'a list_or_val =
L of 'a list_or_val list
| A of 'a
然后你访问最左边的值如下:
let rec leftmost_value term = match term with
| L ([]) -> failwith "Unexpected"
| L (x::_) -> leftmost_value x
| A v -> v;;
例如:
# leftmost_value (L [A 5; A 3]);;
- : int = 5
我从 ocaml 开始,我想知道如何在类型的递归函数中 '一个列表 -> int ,
let rec int l =
match l with
| [] -> 0
| hd::tl -> 10
仅在必要时才可以展平列表 例如,如果 [0;2;3;4] 只是 return 的整数 如果 [[0];2; [3;4]],然后执行 -> [0;2;3;4] 然后 return int.
提前致谢。
您不能直接存储列表或列表中的数字,因为列表必须存储相同类型的值。
但是,您可以为这两种值声明一个变体类型(标记联合)。
这里的类型 'a lisr_or_val
表示的值要么是类型 'a
的值,例如表示为 (A 3)
,要么是类型 'a lisr_or_val
的值列表,例如示例 (L [(A 3); (A 5)])
:
type 'a list_or_val =
L of 'a list_or_val list
| A of 'a
然后你访问最左边的值如下:
let rec leftmost_value term = match term with
| L ([]) -> failwith "Unexpected"
| L (x::_) -> leftmost_value x
| A v -> v;;
例如:
# leftmost_value (L [A 5; A 3]);;
- : int = 5