F#:将字符串选项转换为字符串的最短方法 [英] F#: shortest way to convert a string option to a string

查看:85
本文介绍了F#:将字符串选项转换为字符串的最短方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是将来自某些类型正确的计算的string option转换为普通的string,然后可以将其传递到UI/printf/URL/其他只需要字符串并知道的内容没有任何期权类型. None应该只是成为空字符串.

The objective is to convert a string option that comes out of some nicely typed computation to a plain string that can then be passed to the UI/printf/URL/other things that just want a string and know nothing of option types. None should just become the empty string.

显而易见的方法是在输入上执行matchif:

The obvious way is to do a match or an if on the input:

input |> fun s -> fun s -> match s with | Some v -> v | _ -> ""

input |> fun s -> if s.IsSome then s.Value else ""

但是尽管它们仍然是单行,但是它们仍然占用了大量的行空间.我希望能找到最短的方法.

but while still being one-liners, these still take up quite a lot of line space. I was hoping to find the shortest possible method for doing this.

推荐答案

您还可以使用函数defaultArg input "",在您使用正向管道的代码中,该函数将是:

You can also use the function defaultArg input "" which in your code that uses forward pipe would be:

input |> fun s -> defaultArg s ""

这是另一种写法,但没有lambda:

Here's another way of writing the same but without the lambda:

input |> defaultArg <| ""

如果在F#内核中有一个参数被翻转的版本会更好.我仍然认为这是不中继其他库或用户定义函数的最短方法.

It would be better if we had a version in the F# core with the arguments flipped. Still I think this is the shortest way without relaying in other libraries or user defined functions.

更新

现在在F#4.1中,FSharp.Core提供的Option.defaultValue相同,但参数已翻转,因此现在您可以简单地编写:

Now in F# 4.1 FSharp.Core provides Option.defaultValue which is the same but with arguments flipped, so now you can simply write:

Option.defaultValue "" input

哪个对管道友好:

input |> Option.defaultValue ""

这篇关于F#:将字符串选项转换为字符串的最短方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆