List.reduce partial application with type annotation gives error FS0030

let ones = List.map (fun _ -> 1)

It is not possible to generalize and produces a value of FS0030.

This can be fixed (among other things) with an annotation like:

let ones<'a> : 'a list -> int list = List.map (fun _ -> 1)

However, in the case of:

let count = List.fold (fun t _ -> t + 1) 0

What type of annotation will work, or why doesn't it add type annotation to the compiler?

let count : 'a list -> int = List.fold (fun t _ -> t + 1) 0

(I know about List.length or I can use count x = x |> List.fold .. etc., what I'm trying to understand is why the type annotation is used for the List.map example, but not List.reduce)

+4
source share
2 answers

Short answer

This is the correct syntax:

let count<'a> : 'a list -> int = List.fold (fun t _ -> t + 1) 0

Description

This is not a type annotation that helps; it is a general parameter.
This compiles (and even works, sort of):

let count<'a> = List.fold (fun t _ -> t + 1) 0

FS0030 , . , ( ), . , , . , , , , , , .

, . , F # count, , obj list -> int.

? - :

let count<'a> = List.fold (fun t _ -> t + 1) 0
let c = count [1..5]

count - int list -> int.

? : -)

let count<'a> = List.fold (fun t _ -> t + 1) 0
let c = count [1..5]
let c2 = count ["a"; "b"; "c"]

, , , "a", "b" "c" int.

WTF?
F # - "" , . count obj list -> int (obj ), int list, int list -> int. string list , .

:

let add x y = x + y
add 2.0 4.5
add "a" "b"

int -> int -> int, , add float -> float -> float ( ), , -, .

, :

let count<'a> : 'a list -> int = List.fold (fun t _ -> t + 1) 0

count .

+4
let count<'a> : 'a list -> int = List.fold (fun t _ -> t + 1) 0
+3

All Articles