作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
以此代码为例,如何检查输入是否为空?类似的代码抛出空引用异常
let private Method ( str:string) : string =
let a = str
a.[a.Length-1]
最佳答案
虽然 isNull
是一个 super 简单的答案并且完全有效,我认为与其他一些人一起玩会很有趣,因为 F# 很有趣 :)
首先让我们设置一个小函数来快速测试结果
open System
let test f a =
try
printfn "Input %A, output %A" a (f a)
printfn "Input %A, output %A" "" (f "")
printfn "Input %A, output %A" null (f null)
with
| :? Exception as ex -> printfn "%s" ex.Message
//string -> string
let getLast1 ( s:string) : string = s.[s.Length-1] |> string
printfn "=== getLast1 ==="
test getLast1 "bing"
=== getLast1 ===
Input "bing", output "g"
Index was outside the bounds of the array.
if
检查值如果不是有效值,则返回空字符串。
//string -> string
let getLast2 ( s:string) : string =
if (String.IsNullOrEmpty s) then ""
else s.[s.Length-1] |> string
printfn "=== getLast2 ==="
test getLast2 "bing"
=== getLast2 ===
Input "bing", output "g"
Input "", output ""
Input , output ""
option
使用模式匹配
//string -> string option
let getLast3 (s:string) =
match s with
| null -> None
| _ ->
match (s.ToCharArray()) with
| [||] -> None
| [|x|] -> Some x
| xs -> Array.tryLast xs
|> Option.map string
printfn "=== getLast3 ==="
test getLast3 "bing"
=== getLast3 ===
Input "bing", output Some "g"
Input "", output <null> //note that <null> is actuallyNone
here.
Input <null>, output <null> //note that <null> is actuallyNone
here.
//'a -> 'a option
let sanitize x = if (isNull x) then None else Some(x)
//string -> char[]
let toCharArray (s:string) = s.ToCharArray()
//'a[] option -> 'a option
let last xs =
xs |> Option.map Array.tryLast //tryLast returns an 'a option
|> Option.flatten // turns 'a option option to a' option
//string -> string option
let getLast4 s =
s |> sanitize
|> Option.map toCharArray
|> last
|> Option.map string
printfn "=== getLast4 ==="
test getLast4 "bing"
=== getLast4 ===
Input "bing", output Some "g"
Input "", output <null> //note that <null> is actuallyNone
here.
Input , output <null> //note that <null> is actuallyNone
here.
getLast2
可能没问题。如果我发现自己在检查空字符串,我宁愿返回
Some
或
None
来自
if
.我只是想展示如何远离
null
并使用内置
Array
职能。
关于f# - 如何在F#中检查值是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51079733/
我是一名优秀的程序员,十分优秀!