我刚刚进行了CodeWars练习-“创建一个接受非负整数和字符串列表并返回过滤掉字符串的新列表的函数”。
我的解决方案使用List.filter,但在其中一种极端情况下失败了。因此,我查看了他们的解决方案,并使用了List.choose-它似乎与我的版本几乎相同,只是在决定是否将结果包括在新列表中之前,将结果转换为选项。
我很困惑-有人可以解释什么时候最好使用“选择”,什么时候最好使用“过滤器”?
我认为您已经观察到了答案的实质:filter允许您测试条件,但同时choose您也可以使用相同的表达式来投影您的值,map如果使用,则需要单独的值filter。
由于问题陈述不清楚(一个列表不能同时包含整数和字符串,除非将它们装在盒子中;即列表的类型为obj list),所以我们可以研究这两种情况。map使用时请注意其他功能filter。
// List of strings that may contain integer representations
["1"; "abc"; "2"; "def"]
|> List.choose (System.Int32.TryParse >> function
| true, i -> Some i
| _ -> None )
["1"; "abc"; "2"; "def"]
|> List.map System.Int32.TryParse
|> List.filter fst
|> List.map snd
Run Code Online (Sandbox Code Playgroud)
这两个表达式都返回int list = [1; 2]。
// List of object that are either of type int or of type string
[box 1; box "abc"; box 2; box "def"]
|> List.choose (function
| :? int as i -> Some i
| _ -> None )
[box 1; box "abc"; box 2; box "def"]
|> List.filter (fun i -> i :? int)
|> List.map unbox<int>
Run Code Online (Sandbox Code Playgroud)
在obj list作为输入的情况下,投影用于提供正确的结果类型。可以通过其他方式完成此操作,例如,使用带注释的let绑定。
最后,两者之间的决定取决于您的个人喜好。
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |