らくがき

2008/03/17

[F#] ネストしたリストをフラットにする

ネストしたリストをフラットにするコード
type 'a tree =
   | E of 'a   // Element
   | N of 'a tree list // Node

let rec flattenTree (t:'a tree) : 'a list =
   match t with
   | E e -> [e]
   | N n -> List.flatten(List.map flattenTree n)
使用例:
let t1 = N [ E 1; N [E 2; E 3]; E 4 ]
flattenTree t1
flattenTree (N [ E "a"; N [ E "b"; E "c"]; E "d" ] )
結果:
> val it : int tree = N [E 1; N [E 2; E 3]; E 4]
> val it : int list = [1; 2; 3; 4]
> val it : string list = ["a"; "b"; "c"; "d"]
ふむふむ・・・なんとなくおk!  

Labels:

0 Comments:

Post a Comment

<< Home