Reputation: 189
I have just started with F# and functional programming. I want to know how I can make a function taking a tuple where I define that the first value have to be a string, instead of the standard int.
Example:
A function which replicates a string, s
, n
times and returns it. What i have right now is this:
let rec pow2 = function
| (s:string,0) -> ""
| (s:string,n) -> s + pow2(s,n-1)
This works, but I think that there is a better way than defining s:string
every case.
(I know String.replicate
, this is not for the sake of the effect, but learning)
Upvotes: 2
Views: 191
Reputation: 7676
You can also do it like this, where the type of the tuple is given in the function definition:
let rec pow2 ((s, n) : string * int) =
match n with
| 0 -> ""
| _ -> s + pow2 (s, n - 1)
Note that elements of a tuple are seperated by *
in the explicit type annotation. Also, as Stephen pointed out, the type inference system will, in this example, be smart enough to figure out the type of tuple because we match n
with an integer and because we add a string (""
) to s
.
Upvotes: 4
Reputation: 11525
You only need the type annotation on the first case -- the F# compiler can infer that the first element of the tuple must be a string
in the rest of the cases.
let rec pow2 = function
| (s:string,0) -> ""
| (s,n) -> s + pow2(s,n-1)
It's just a matter of style, but I think it's a little easier to read if you write the function like this:
let rec pow2 (s, n) =
match n with
| 0 -> ""
| _ -> s + pow2(s, n-1)
Upvotes: 4
Reputation: 22297
In fact, no type annotations are required here. The ""
return value in the the first pattern match is a sufficient enough hint for the compiler:
> let rec pow2 = function
| (s,0) -> ""
| (s,n) -> s + pow2(s,n-1);;
val pow2 : string * int -> string
Upvotes: 7