kam
kam

Reputation: 669

Arbitrary arrays handling F#

I'm trying to make a module in F# where i need to have some types consisting of array's of some arbirary type and with som arbitrary length.

to come with an example lets say i need to make a module for arbitrary large vector calculations.

then my idea is

module Vector =
type Vector = V of array<_>
let (+) (v1:Vector) (v2:Vector) = Vector.map2 (+) V1 V2

but this is not working because the map2 function are not declaret for vectors yet and that's is the question, How do I declare the map2 function for an new type with the same proberties ad an array?

Upvotes: 2

Views: 92

Answers (1)

Gus
Gus

Reputation: 26174

The function map2 already exists for arrays, so you can reuse it.

But please note that if you use a let-bound function for (+) it will be accesible only inside the type, so you should use a static member instead.

Then to call the existing map2 function you can use pattern matching to de-compose your Single-Case Discriminated-Union:

type Vector<'t> = V of array<'t> with
    static member (+) (V v1, V v2) = V (Array.map2 (+) v1 v2)

But if you still want to create the map2 function for your type, in order to use it in a more generic way you can create it like this:

type Vector<'t> = V of array<'t> with
    static member map2  f (V v1) (V v2) = V (Array.map2 f v1 v2)
    static member (+) (v1, v2) = Vector<_>.map2 (+) v1 v2

Upvotes: 4

Related Questions