문제

I've started learning F# and I'd like to write my own map function using tail-recursion. Here is what I have

let my_map ff list =
    let rec mapAcc ff_inner list_inner acc =
        match list_inner with
        | [] -> acc
        | front::rest -> mapAcc( ff_inner rest (ff_inner(front) :: acc) ) //error
    mapAcc ff list []

It would be called like this:

let list = my_map (fun x -> x * 2) [1;2;3;4;5] // expect [2;4;6;8;10]

I get an compilation error message on the second condition that says Type mismatch. Expecting a 'a but given a 'b list -> 'a -> 'a The resulting type would be infinite when unifying ''a' and ''b list -> 'a -> 'a'

I don't know what this error message means. I'm not sure how this can be infinite if I am passing the rest in the recursive call to mapAcc.

Note: I realize I'm rebuilding the list backwards. I'm ignoring that for now.

도움이 되었습니까?

해결책

Just remove the parenthesis when the function calls itself:

let my_map ff list =
    let rec mapAcc ff_inner list_inner acc =
        match list_inner with
        | [] -> acc
        | front::rest -> mapAcc ff_inner rest (ff_inner(front) :: acc)
    mapAcc ff list []

otherwise everything contained there is interpreted as a single parameter and ff_inner as a function call with the rest as parameters.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top