I am interested create a function with return value int32 or float32 or float

Off the top of my head:

1
2
3
4
5
6
7
8
9
10
11
type Number =
    | Int of int
    | Float of float
    | Float32 of float32

// int -> Number list
let mylist n =
    match n with
    | 1 -> [Int(1);Int(1),Int(1)]
    | 2 -> [Float32(1.0f);Float32(1.0f);Float32(1.0f)]
    | _ -> [Float(1.0);Float(1.0);Float(1.0)]

A completely different approach, using Math.INumeric:

1
2
3
4
5
// INumeric<'num> -> 'num list
let mylist (numeric:Math.INumeric<'num>) : 'num list =
    let one = numeric.One
    [one;one;one]// usage:
let theList = mylist Math.Instances.FloatNumerics
By on 9/30/2008 4:50 AM ()

Coming from an object-oriented world I would assume that int, float, etc. all inherit from Object (in some way) and thus

1
let mylist n : list<obj> = .....

should do the trick as well. You may need to 'box' the types (because they are implemented as primitives and not objects. -> [box 1.0, box 2.0, ...])

Maybe there's even something better than Object from which all those types inherit. Like Numeric,... ?
This would keep you from loosing all the static type information.

By on 8/25/2008 1:17 AM ()

Hello, jonaas.

You must join types you like to use into one type. So you have next ways:
- to return tuple of types:

1
2
3
4
5
6
7
8
9
(*
  val mylist : int -> int list * float32 list * float list
 example of usage: _,flst,_ = mylist 2
 *)
let mylist n =
    match n with
    | 1 -> [1;1;1],[],[]
    | 2 -> [],[1.0f;1.0f;1.0f],[]
    | _ -> [],[],[1.0;1.0;1.0]

- to return discriminated union type of all possible list (or element) types:

1
2
3
4
5
6
7
8
9
10
11
type MyList = 
  |IntList of int list
  |F32List of float32 list
  |FList of float list

(* val mylist : int -> MyList *)
let mylist n =
    match n with
    | 1 -> IntList([1;1;1])
    | 2 -> F32List([1.0f;1.0f;1.0f])
    | _ -> FList([1.0;1.0;1.0])

- to store your data in one format and to use views to convert it to other formats (f.e. with active patterns):

1
2
3
4
5
6
7
8
9
10
11
type Base = int list
let (|F32List|) (l: Base) = List.map float32 l
let (|FList|) (l: Base) = List.map float l
(*
  usage examples:
  let FList(f) = [1;2;3]
  or
  let f32 = match [3;4;5] with F32List(l) -> l
 *)

- of course, there is more techniques to use: records, classes, ...

By on 8/23/2008 7:07 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper