3

Is there any built-in way in F# to convert from true to 1 and false to 0? This is simple in languages like C, C++ etc.

As a bit of background I am trying to solve an exercise in a textbook (exercise 2.4 in Functional Programming Using F#), which asks for an F# function occFromIth(str,i,ch) that returns the number of occurrences of character ch in positions j in the string str with j >= i.

My solution is

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)

but I don't like the code duplication so I wrote

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)

I guess another alternative is to use if... then... else..., in the style of the C/C++ conditional operator

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)

or

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)

What is the way to do this in F#?

4

3 回答 3

6

System.Convert.ToInt32(bool)--我对F#不太熟悉,但我相信无论是否内置,使用函数都是一样的:function(arg0, arg1, ...)。因此,在这种情况下,您只需调用System.Convert.ToInt32(myBool).

于 2013-09-08T12:24:55.773 回答
5

您实际上并不需要将 bool 转换为 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 
于 2013-09-08T15:53:02.440 回答
-2

制作函数或使用内置函数是有区别的。任何比较的CPU指令都返回转换为1和0的位模式的结果。这可用于进行无分支编程,取决于情况比分支更有效. 可以在没有分支的情况下找到与值的比较

   Int min(int a, int b) {
         Int temp = a < b;
         Return a*temp + b*(1-temp);
   }
于 2021-03-21T08:01:57.900 回答