Binding values with list matching (without compiler warning)

半腔热情 提交于 2019-12-10 15:22:46

问题


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

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

Instead, I want to do this:

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

I'd like to do this:

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

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?


回答1:


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)

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.

Sample usage (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

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




回答2:


The incomplete pattern warning is because there is a case that you forgot: the case of the empty list [].

Are you obligate to use x,y,z ... ? This is work : let l = List.map float32 [x;y;w;h] without warning.



来源:https://stackoverflow.com/questions/30622850/binding-values-with-list-matching-without-compiler-warning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!