【问题标题】:Combining two functions in OCaml在 OCaml 中组合两个函数
【发布时间】:2016-11-04 16:55:01
【问题描述】:

我的任务是从列表中删除重复项。为此,我必须先对列表进行排序。

我已经编写了对列表进行排序的函数和删除列表的函数 重复(排序后),但我不知道如何组合它们。

例子:

输入:[4;5;2;2;1;3;3]

输出:[1;2;3;4;5]

let rec setify = function
    | [] -> []
    | x :: l -> insert x (setify l)
  and insert elem = function
    | [] -> [elem]
    | x :: l -> if elem < x then elem :: x :: l
                else x :: insert elem l;;

let rec rem =function 
|[] -> [] 
| x :: []-> x :: [] 
| x :: y :: rest -> if x = y then rem (y :: rest) 
                    else x :: rem (y :: rest) ;;

【问题讨论】:

  • 好吧,假设你有一个函数加了十:let addten x = x + 10 和一个函数乘以两个 let double x = x * 2。您将如何从这两个函数中创建一个函数,该函数取一个数字,加十,然后将结果乘以二?
  • 顺便说一句:这是一种奇怪的解决问题的方法。如果你想生成一个没有重复的排序列表,那么你只需说| x :: l -&gt; if elem &lt; x then elem :: x :: l else if elem = x then x :: l else x :: insert elem l;; - 如果列表中有重复项,则根本不要插入该项目!
  • 最后:你能让你的插入方法尾递归吗?

标签: ocaml


【解决方案1】:

您希望创建一个接受列表、创建排序列表并对其进行重复数据删除的函数。换句话说,你想要:

let task list =
  let sorted_list = setify list in
  rem sorted_list

可以以任意更复杂的方式执行此操作,但以上是一个简单的、每行一个操作的版本。由于您的问题标题的措辞邀请它,这里是更复杂的方法之一:

(* it's possible to write a generic combinator of functions, that takes two functions f and g *)
let combine f g =
(* and returns a function *)
fun x ->
(* that maps x to f(g(x)) *)
f (g x)

(* this function is typed as:
val combine : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b = <fun>
*)

(* the task can then be expressed as the combination of setify and rem: *)
let task = combine rem setify

除非确实从中获得了一些东西,否则不要使用这种风格。大多数 它只会使程序的可读性降低和速度变慢而没有相应的好处。 *)

【讨论】:

    猜你喜欢
    • 2021-02-19
    • 2018-06-29
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多