How can i convert between F# List and F# Tuple?

前端 未结 5 990
Happy的楠姐
Happy的楠姐 2020-11-30 10:45

Is there some way to convert between F# List and F# Tuple?

For example:

[1;2;3] -> (1,2,3)    
(1,2,3,4) -> [1;2;3;4]

I need

5条回答
  •  無奈伤痛
    2020-11-30 11:30

    Making use of the PropertyInfo structure one can build a list recursively. A problem with this approach is that the type information is lost and the result is produced as a list of obj. Nevertheless, this does solve the tuple to list portion of the question.

    let tupleToList tpl = 
        let rec loop tpl counter acc =
            let getItemPropertyInfo t n = t.GetType().GetProperty(sprintf "Item%d" n)
            let getItem t n = (getItemPropertyInfo t n).GetValue(t,null)
            match counter with
            | 8 -> 
                match tpl.GetType().GetProperty("Rest") with
                | null -> acc
                | _ as r ->
                    let rest = r.GetValue(tpl,null)
                    loop rest 2 ((getItem rest 1) :: acc)
            | _ as n -> 
                match getItemPropertyInfo tpl n with
                | null -> acc
                | _ as item -> loop tpl (counter+1) (item.GetValue(tpl,null) :: acc)
        loop tpl 1 [] |> List.rev
    

提交回复
热议问题