有没有办法做多值比较内联? [英] Is there a way to do a multiple value comparison inline?

查看:120
本文介绍了有没有办法做多值比较内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得傻,甚至问这个,因为它似乎这么琐碎,但我的大脑是失败了我。如果我有以下:

 让a,b,c = 1,1,1 

是否有合格的方法来确定a,b和c是否都保持相同的值。例如:

  let result =(a = b = c)
pre>

这会失败,因为表达式 a = b 返回true,下一个表达式导致 true = c 并且抱怨它是期望int,而不是bool。我唯一能想到的是:

  a = b&& a = c&&当我想添加更多变量时,b = c 

b
$ b

我真正想做的是:

  string * string * string)= 
match x with
| (a,a,a) true
| _ - > false



我希望我可以将所有元素匹配到一个元素,如果他们不同

解决方案

要检查每个值是否已经被绑定,在列表中是相同的:

  let rec same = function 
|当x<>时,x :: y :: _ y - > false
| _ :: xs - > same xs
| [] - > true

使用

 code> let a,b,c = 1,1,1 
same [a; b; c] // true


I feel silly for even asking this because it seems so trivial but my brain is failing me. If I had the following:

let a, b, c = 1, 1, 1

Is there an eligant way to determine if a, b, and c all hold the same value. Something like:

let result = (a = b = c)

This fails because the expression a = b returns true and the next expression results in true = c and complains that it was expecting int, not bool. The only thing I can think of is:

a = b && a = c && b = c

which won't work when I want to add more variables.

Really what I'm trying to do is this:

let same (x: string * string * string) =
    match x with
    | (a, a, a) -> true
    | _ -> false

I was hoping that I could match all the elements into one element and if they were different it would move on, but it says on the second element in the match that it has already been bound.

解决方案

To check if every value in a list is the same:

let rec same = function
  | x::y::_ when x <> y -> false
  | _::xs -> same xs
  | [] -> true

Usage

let a, b, c = 1, 1, 1
same [a; b; c] //true

这篇关于有没有办法做多值比较内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆