0 people like it.

Flatten Nested Type

Flatten Nested Type

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
type NestedType<'a> = List of NestedType<'a> list | E of 'a

let flatten ls =
    let rec start temp input = 
        match input with
        | E e -> e::temp
        | List es -> List.foldBack(fun x acc -> start acc x) es temp
    start [] ls

// test (a (b (c d) e)))
(List [E "a"; List [E "b" ; List [E "c";  E "d"]; E "e"]]) |> flatten = ["a";"b";"c";"d";"e";]
Multiple items
union case NestedType.List: NestedType<'a> list -> NestedType<'a>

--------------------
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
type NestedType<'a> =
  | List of NestedType<'a> list
  | E of 'a

Full name: Script.NestedType<_>
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
union case NestedType.E: 'a -> NestedType<'a>
val flatten : ls:NestedType<'a> -> 'a list

Full name: Script.flatten
val ls : NestedType<'a>
val start : ('b list -> NestedType<'b> -> 'b list)
val temp : 'b list
val input : NestedType<'b>
val e : 'b
val es : NestedType<'b> list
val foldBack : folder:('T -> 'State -> 'State) -> list:'T list -> state:'State -> 'State

Full name: Microsoft.FSharp.Collections.List.foldBack
val x : NestedType<'b>
val acc : 'b list
Raw view Test code New version

More information

Link:http://fssnip.net/qT
Posted:9 years ago
Author:Pitch Rock
Tags: flatten