F# member constraints + ^a byref parameters

前端 未结 3 759
执念已碎
执念已碎 2020-12-17 21:03

After some playing around F# member constraints feature and writing function like this:

let inline parse< ^a when ^a : (static member Parse: string ->          


        
3条回答
  •  一整个雨季
    2020-12-17 21:47

    This compiles but still does not work as expected:

    let inline tryParse< ^a when ^a: (static member TryParse: string -> ^a ref -> bool) > s =
      let x = ref Unchecked.defaultof< ^a>
      match (^a: (static member TryParse: string -> ^a ref -> bool )  (s, x)) with
        | false -> None
        | true -> Some(!x)
    
    // returns [Some 0; Some 0; Some 0; null], so our tryParse is not retrieving the value from the ref
    let xs = [ "1"; "456"; "999"; "a" ] |> List.map tryParse
    

    in this specific case, rather than using reflection I would just recreate TryParse out of Parse in f#

    let inline tryParse< ^a when ^a: (static member Parse: string -> ^a) > s =
      try  
        Some(^a: (static member Parse: string -> ^a)  s)
      with
        | exn -> None
    
    let xs = [ "1"; "456"; "999"; "a" ] |> List.map tryParse
    

提交回复
热议问题