Nair
Nair

Reputation: 7458

why function call returns error?

I am trying out the following code in F# interactive and getting 'error FS0001: the type 'int -> int' does not match the type 'int'. Here is the code I am trying

> let rec factorial n = function
    | 0 -> 1
    | n -> n * factorial (n - 1);;

This is off of 'F3 for scientist' book example. Thanks,

Upvotes: 1

Views: 114

Answers (2)

Tomas Petricek
Tomas Petricek

Reputation: 243096

Just to add some details about the syntax - the function keyword creates a function that takes an argument (implicitly, without naming it) and then allows you to pattern match on that value.

There are quite a few equivalent ways of doing this - using function as ildjarn described:

let rec factorial = function
  | 0 -> 1
  | n -> n * factorial (n - 1)

You can also declare factorial as a function taking n and then use match:

let rec factorial n = 
  match n with
  | 0 -> 1
  | n -> n * factorial (n - 1)

And for completeness, you can also create a function using fun (which is a simpler version of function that does not give you the ability to write multiple cases of pattern matching):

let rec factorial = fun n ->
  match n with
  | 0 -> 1
  | n -> n * factorial (n - 1)

The first two options are both idiomatic F# code - the second one is slightly more complex (without any good reason), so I'd prefer one of the first two.

Upvotes: 4

ildjarn
ildjarn

Reputation: 62995

As you've defined it, factorial takes two arguments, but you're only passing it one. Consequently, the second branch of the function is trying to multiply an int with a partially applied function of type int -> int.

The first line should read

let rec factorial = function

(sans n).

Upvotes: 3

Related Questions