4
votes

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?

2

2 Answers

3
votes

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. ;)

0
votes

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.