F# F将字符串拆分为元组的最简单方法 tl;博士

F# F将字符串拆分为元组的最简单方法 tl;博士,f#,F#,我应该像下面那样实现每个helper函数吗 设splittotuple2str= 将str.Split与匹配 |[a;b |]->a,b |大小必须为2的故障 让我们拆分为3个str= 将str.Split与匹配 |[a;b;c]->a,b,c |大小必须为3的故障 让我们拆分为4个str= 将str.Split与匹配 |[a;b;c;d]->a,b,c,d |大小必须为4的故障 动机 字数是预先知道的 设str=first-second-third//每个单词用空格分隔 下面的内容足以满足我的

我应该像下面那样实现每个helper函数吗

设splittotuple2str= 将str.Split与匹配 |[a;b |]->a,b |大小必须为2的故障 让我们拆分为3个str= 将str.Split与匹配 |[a;b;c]->a,b,c |大小必须为3的故障 让我们拆分为4个str= 将str.Split与匹配 |[a;b;c;d]->a,b,c,d |大小必须为4的故障 动机 字数是预先知道的

设str=first-second-third//每个单词用空格分隔 下面的内容足以满足我的需要

设arr=str.Split 设a=arr[0]//首先 设b=arr[1]//秒 设c=arr[2]//第三 不过,我想用一行来做这些

let[|a;b;c |]=str.Split//警告:此表达式上的模式匹配不完整。 nowarn 25是不利的,因为它会影响整个文件

在这种情况下,我需要将字符串拆分为string*string*string,以避免出现警告

设a,b,c=str |>splitToTuple3
我应该实现开头提到的每个helper函数吗?

一般来说,是的,在您的情况下必须创建三个单独的函数,因为每个函数返回不同的数据类型—两个、三个或四个元素的元组。 您可能会考虑创建一个区分联盟来覆盖所有只需要一个函数的情况,例如

module Split = 
    
    let split (str:string) = str.Split() 

    type SplitterTuple<'t> =
    | Two of 't * 't
    | Three of 't * 't * 't
    | Four of 't * 't * 't * 't

    let getTuple<'t> (l : 't array) : SplitterTuple<'t> = 
        match l with
        | [|a; b; c; d|] -> Four (a, b, c, d)
        | [|a; b; c|]  -> Three (a, b, c)
        | [|a; b|] -> Two (a, b)
        | _ -> failwith "Incompatible list"

您可能想考虑使用记录类型而不是元组,因为它可能更容易处理。

//test code
    let t1 = "first" |> split |> getTuple |> displayResult //fails
    let t2 = "first second" |> split |> getTuple |> displayResult
    let t3 = "first second third" |> split |> getTuple |> displayResult
    let t4 = "first second third fourth" |> split |> getTuple |> displayResult
    let t5 = "first second third fourth fifth" |> split |> getTuple  |> displayResult //fails

数组let绑定出现警告,但元组let绑定没有。为什么不让words=str.Split?字符串总是有2、3或4个单词?没有其他情况吗?我建议使用F+函数sscanf,这样就可以使用任意元组大小的t1、t2、t3=sscanf%s%s第一个第二个第三个,依此类推。对于处理故障,您可以使用try版本。您也可以自己编写函数,但这不是一件小事。
//test code
    let t1 = "first" |> split |> getTuple |> displayResult //fails
    let t2 = "first second" |> split |> getTuple |> displayResult
    let t3 = "first second third" |> split |> getTuple |> displayResult
    let t4 = "first second third fourth" |> split |> getTuple |> displayResult
    let t5 = "first second third fourth fifth" |> split |> getTuple  |> displayResult //fails