Search code examples
f#value-restriction

Define sum of square without defining parameter


I want to define sumOfSquares without explicity using parameter, relying instead on functional composition

Here's my code below

let sumOfSquares = Seq.map (fun n -> n * n) >> Seq.sum

However, I got the following error

stdin(80,5): error FS0030: Value restriction. The value 'sumOfSquares' has been inferred to have generic type

val sumOfSquares : ('_a -> int) when '_a :> seq<int> 

Either make the arguments to 'sumOfSquares' explicit or, if you do not intend for it to be generic, add a type annotation.

One way to resolve it is by using parameters

let sumOfSquares nums = nums |> Seq.map (fun n -> n * n) |> Seq.sum

and this will work. However, I want to see if I can define sum of squares by using composition alone

Update

Here's a nice article describing the issue I've encountered: Value Restriction.


Solution

  • Make a type annotation:

    let sumOfSquares : seq<int> -> int = 
        Seq.map (fun n -> n * n) >> Seq.sum