F#中是否有任何内置方式可以转换true为1和转换false为0?这在C,C++等语言中很简单.
作为一个有点背景的,我试图解决在课本练习(练习2.4 函数式编程使用F# ),它要求的F#函数occFromIth(str,i,ch)返回字符出现的次数ch在位置j字符串中str使用j >= i.
我的解决方案是
let rec occFromIth (str : string, i, ch) =
if i >= str.Length then 0
else if i < 0 || str.[i] <> ch then occFromIth(str, i+1, ch)
else 1 + occFromIth(str, i+1, ch)
Run Code Online (Sandbox Code Playgroud)
但我不喜欢代码重复,所以我写了
let boolToInt = function
| true -> 1
| false -> 0
let rec occFromIth (str : string, i, ch) =
if i >= str.Length then 0
else boolToInt (not (i < 0 || str.[i] <> ch)) + occFromIth(str, i+1, ch)
Run Code Online (Sandbox Code Playgroud)
我想另一种选择是使用if... then... else...C/C++ 条件运算符的样式
let rec occFromIth (str : string, i, ch) =
if i >= str.Length then 0
else (if (not (i < 0 || str.[i] <> ch)) then 1 else 0) + occFromIth(str, i+1, ch)
Run Code Online (Sandbox Code Playgroud)
要么
let rec occFromIth (str : string, i, ch) =
if i >= str.Length then 0
else (if (i < 0 || str.[i] <> ch) then 0 else 1) + occFromIth(str, i+1, ch)
Run Code Online (Sandbox Code Playgroud)
在F#中这样做的方法是什么?
System.Convert.ToInt32(bool) - 我对F#不太熟悉,但我相信使用函数是否相同无论是否内置:function(arg0,arg1,...).所以,在这种情况下,你只需要打电话System.Convert.ToInt32(myBool).
您实际上不需要布尔值将int或int转换为bool即可,因为您可以实现以下结果:
let occFromIth (str : string, i, ch) =
str
|> Seq.mapi (fun j c -> (j,c))
|> Seq.filter (fun (j,c) -> j >= i && c = ch)
|> Seq.length
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2252 次 |
| 最近记录: |