列表中的术语如何匹配

时间:2018-10-12 20:28:45

标签: visual-studio f#

下面是我的代码,但是在“ CODE HERE”(代码在这里)的地方,我想将某些城市与列表中的城市相匹配。

因此,例如,如果通过功能运行列表中的城市,我希望它输出最后带有“ city”的城市。可能吗?

当然,大约有40个城市应该在列表中,但我没有将它们包括在内。

let listStackOverFlowExample = ["Kansas","Iowa"]


let cityAddCity (city:string) =
    | CODE HERE -> 
         city + " City"

2 个答案:

答案 0 :(得分:2)

您可以将when子句与List.contains组合在一起,以确定输入城市是否在列表中。示例代码:

let listStackOverFlowExample = ["Kansas"; "Iowa"]

let cityAddCity (city : string) =
    match city with
    | s when List.contains s listStackOverFlowExample -> sprintf "%s City" s
    | _  -> sprintf "%s is not in the list" city // Replace accordingly

测试代码:

printfn "%s" <| cityAddCity "Kansas"
printfn "%s" <| cityAddCity "Tokyo"

输出:

Kansas City 
Tokyo is not in the list

答案 1 :(得分:0)

这是带有活动模式的实现。它与Samantha的相同,除了when后卫移出比赛表达式之外。在这种情况下,它没有太大的优势,但是当您要检查的案件数量更多时,它可以通过将详细信息移到其他位置(同时使它们可重复使用)来显着清除匹配表达式。

let listStackOverFlowExample = ["Kansas"; "Iowa"]

let (|InList|_|) list item =
    if list |> List.contains item then Some item else None

let cityAddCity (city : string) =
    match city with
    | InList listStackOverFlowExample city  -> sprintf "%s City" city
    | _  -> sprintf "%s is not in the list" city // Replace accordingly