绑定值与列表匹配(无编译器警告) [英] Binding values with list matching (without compiler warning)

查看:58
本文介绍了绑定值与列表匹配(无编译器警告)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个函数,该函数带有一些int参数,但在其中将使用float32.

Let's say I have a function that takes some int parameters, but inside which I will use float32.

我不想在任何地方都不使用float32 i函数.

I'd prefer not to use the float32 i function everywhere.

相反,我想这样做:

let x = float32 x
let y = float32 y
let w = float32 w
let h = float32 h

要稍微收紧它,我可以这样做:

To tighten it up a bit, I could do this:

let x, y, w, h = float32 x, float32 y, float32 w, float32 h

我想这样做:

let [x;y;w;h] = List.map float32 [x;y;w;h]

这行得通,但是我收到了Incomplete pattern matching on this expression的编译器警告,因为没有静态检查,rhs将恰好有4个项目(可能为空,可能有1个项目,可能有1000个项目).

This works, but I get a compiler warning of Incomplete pattern matching on this expression, because there is no static check that the rhs will have exactly 4 items (could be empty, could have 1 item, could have a thousand).

我不想禁用编译器警告.
这只是一个坏主意吗?在这种情况下,我应该忽略编译器警告,还是有一些不错的惯用法呢?

I don't want to disable the compiler warning.
Is this just a bad idea? Should I ignore the compiler warning in this one case, or is there some nice, idiomatic way to do it?

推荐答案

您可以专门为4元组定义一个映射函数:

You could define a map function specifically for 4-tuples:

let map4 f (x, y, w, h) = (f x, f y, f w, f h)

其类型为f:('a -> 'b) -> x:'a * y:'a * w:'a * h:'a -> 'b * 'b * 'b * 'b.请注意,假定元组中的所有元素都具有相同的类型.

It has the type f:('a -> 'b) -> x:'a * y:'a * w:'a * h:'a -> 'b * 'b * 'b * 'b. Notice that all the elements in the tuple are assumed to have the same type.

样品用量(FSI):

> let x, y, w, h = map4 float32 (1, 2, 3, 4);;

val y : float32 = 2.0f
val x : float32 = 1.0f
val w : float32 = 3.0f
val h : float32 = 4.0f

我将把它留给读者作为练习map2map3等的练习;)

I'll leave it as an exercise to the reader to implement map2, map3, etc. ;)

这篇关于绑定值与列表匹配(无编译器警告)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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