如果大小为< n

问题描述 投票:0回答:0

我有这个 Ocaml 问题: 给出

type 'a stream = Nil | Cons of 'a * (unit -> 'a stream);;

编写函数

take : 'a stream -> int -> 'a list
创建一个包含第一个列表的函数 流的 n 个元素,如果少于
n
个元素,则为所有元素。

我这样做了:

let rec take strm n = 
  match (strm, n) with 
  | _, 0 -> []
  | Nil, _ -> []
  | Cons(h, t), _ -> h::(take (t()) (n-1));;

提出的解决方案是这样的:

let rec take st p = 
  match st with
  | Nil -> []
  | Cons (h, t) -> 
      match p with 
      | 0 -> []
      | n -> (h:: take (t()) (n-1));;

我的版本是首选(假设它是正确的)吗?

functional-programming ocaml
© www.soinside.com 2019 - 2024. All rights reserved.