【问题标题】:OCaml - find all possible variations with repetitionsOCaml - 找到所有可能的重复变化
【发布时间】:2017-03-19 06:41:09
【问题描述】:

我有大约 10 个函数要为其编写测试,它们都采用两个相同类型的参数。我想我可以稍微自动化这个过程,创建一个所有可能输入类的列表,然后将所有可能的变化打印到一个文本文件中。但是,我的代码并不能很好地完成这项工作,只列出了以“a”开头的变体。

let x = ["a "; "b "; "c "; "d "; "e "; "f "; "g "; "h "]
let oc = open_out file

let rec test l1 l2 =
    match l1 with
    |[] -> 0
    |h1::t1 ->
        match l2 with
        |[] -> test t1 l2
        |h2::t2 ->
            fprintf oc "%s\n" (add ^ h1 ^ h2);
            fprintf oc "%s\n" (sub ^ h1 ^ h2);
            fprintf oc "%s\n" (mul ^ h1 ^ h2);
            fprintf oc "%s\n" (div ^ h1 ^ h2);
            test l1 t2;;
test x x;
close_out oc;

【问题讨论】:

    标签: list unit-testing recursion ocaml


    【解决方案1】:

    |[] -> test t1 l2 行中,您使用l2 的空列表进行递归调用。我相信您希望使用初始值l2(在您的示例中为x)进行调用,然后您需要将其存储在实际递归之外的某个位置。类似的东西

    let test original_l1 original_l2 =
      let rec loop l1 l2 =
        ...
          | [] -> loop l1 original_l2
        ...
        in
      loop original_l1 original_l2
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用 Monads(参见ocaml courses 的第 5 页):

      let return x = [x];;
      let bind f l = List.fold_right (fun x  acc -> (f x) @ acc) l [];;
      let (>>=) l f = bind f l;;
      x >>= fun t ->
      x >>= fun t' -> 
      ["add ";"mul ";"sub ";"div "] >>= fun op -> return (op ^ t ^ t') ;;
      

      它将返回一个表示 x * x * Ops 的笛卡尔积的列表。

      可能有更好的方法来使用 ocaml 电池,它似乎实现了做笛卡尔积所需的所有东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        相关资源
        最近更新 更多