3 people like it.

Cast object list

Casts list of objects to any other type. Return objects if cast is possible, so new list can be shorter (or empty).

1: 
2: 
3: 
4: 
5: 
6: 
7: 
let rec cast<'a> (myList: obj list) =          
    match myList with
    | head::tail -> 
        match head with 
        | :? 'a as a -> a::(cast tail) 
        | _ -> cast tail
    | [] -> [] 
val cast : myList:obj list -> 'a list

Full name: Script.cast
val myList : obj list
type obj = System.Object

Full name: Microsoft.FSharp.Core.obj
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
val head : obj
val tail : obj list
val a : 'a

More information

Link:http://fssnip.net/oD
Posted:9 years ago
Author:RLinde
Tags: list; cast; collections