Scott Nimrod
Scott Nimrod

Reputation: 11595

Unable to perform basic arithmetic

In F#, I receive an error when I write the following code:

let records = {1..100}
let middleElement= records |> Seq.length / 2

The type 'int' does not match the type ''a -> int'

I know this error is basic. But I'm new to F# and really don't know what I need to do to resolve this error.

Upvotes: 0

Views: 71

Answers (2)

Phillip Scott Givens
Phillip Scott Givens

Reputation: 5464

I endorse Tomas Petricek's answer, but you could also write it this way. :-)

let records = {1..100}
let middleElement = records |> Seq.length |> (/) <| 2

This says, take the records, feed them to the length function. Feed the result as the first argument to the divide (/) function. This will result in a function which takes an int and returns an int (int -> int). We then feed 2 to that function to get 50.

[Edit] I just realized that this might be even clearer

let records = {1..100}
let middleElement = let length = records |> Seq.length in length / 2;;

Upvotes: 1

Tomas Petricek
Tomas Petricek

Reputation: 243051

You need to add parentheses:

let middleElement = (records |> Seq.length) / 2

In your version, the compiler reads your code as

let middleElement = records |> (Seq.length / 2)

... and it gets confused, because it thinks you are trying to divide the length function by 2!

Upvotes: 6

Related Questions