0
votes

In F#
"Hello"+"World" gives "HelloWorld". I mean the + operator can concatenate the strings.

Given this code:
let iprint list:List<int> =
 let stringList=int2String4List list         //convert the int list to string list
 List.foldBack (fun acc elem -> acc+elem+','  ) stringList  ""

but i faced with the error:

The type 'List<int>' does not match the type 'string'

It seems to me the F# interpreted the datatype of stringList as int meanwhile it is a List<string>. but i do not know how does it happen?

List.foldBack : ('T -> 'State -> 'State) -> 'T list -> 'State -> 'State

This means, the datatype of first parameter of function and the list must be the same, but why it is insisting to accept + as an int operator, but not a string operator?

1
what is the signature of int2String4List function? - Petr
let rec int2String4List (list:List<int>) :List<string> - Jimmy
Change signature of your function: let iprint (list:List<int>) = - Petr

1 Answers

1
votes

You missed parenthesis in your function declaration, so the type annotation (List<int>) was applied to the function return value. This will compile:

let iprint (list:List<int>) =
    let stringList=int2String4List list
    List.foldBack (fun acc elem -> acc+elem+",") stringList  ""

By the way, isn't your int2String4List simply List.map string?

Also, the parameters of fun acc elem -> ... are in the wrong order. If you check the type of the function expected by List.foldBack you will see it's 'T -> 'State -> 'State - the first parameter is an element of the list, the second one is the accumulator. There is not much difference in the sample you posted (both 'T and 'State are string), but there is a difference if you want to shorten it:

let iprint list =
    List.foldBack (fun elem acc -> (string elem) + "," + acc  ) list  ""

As @JoelMueller noticed in his comment, the shortest and fastest way to achieve this result is

let iprint =
    List.map string >> String.concat ","