简体   繁体   English

使用List和couples的Ocaml函数

[英]Ocaml functions using List and couples

I have an assignment to finish but I'm having trouble with it. 我有一个任务要完成,但是我遇到了麻烦。 This is in ocaml and lists are the main focus. 这是在ocaml中,列表是主要焦点。

The first function takes in a list of couples[(a1,b1);(a2,b2)...] and verifies that every "a" are different. 第一个函数接受一对夫妇的列表[(a1,b1);(a2,b2)...]并验证每个“ a”是否不同。

I tried to do this in two parts: 我尝试分两部分进行此操作:

let rec isNotIn x = function
   |[]-> true
   |(a,_)::l -> a <> x && isNotIn a l;;
let isFunction = function
   |[] -> false
   |(a,_)::l -> isNotIn a l;;

I can't find a way to make it work, isFunction only checks if the following couple has the first element equal to its own. 我找不到一种使它起作用的方法,isFunction仅检查以下对夫妇的第一个元素是否等于其自己的元素。 But I need it to check it for every first element of the list, not just the next one. 但是我需要它来检查列表中的每个第一个元素,而不仅仅是下一个。

Well, what you did is almost perfect except you forgot the recursive call : 好吧,除了忘记了递归调用,您所做的几乎是完美的:

let rec isFunction = function
   | []  -> true (* if the function is empty it's ok, no ? *)
   | (a, _) :: l -> isNotIn a l && isFunction l;;

And, actually, your first function doesn't only take a list of couples but takes an element x and verifies that x is not the first element of any couple in the list. 而且,实际上,您的第一个函数不仅接收一对夫妇,而且接收一个元素x并验证x不是列表中任何一对的第一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM