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#?