문제

I've got an F# assignment where I am trying to compute the transpose of a matrix. Simple enough, but I keep getting a value restriction error and I cannot figure out why. I consulted many of the VR error questions that are out there, but I'm still in the dark. Here's my code:

let transpose = function
    | [xs ; ys] -> 
                let rec transpose_helper = function
                    | [],[] -> []
                    | x::xs , y::ys -> [x;y] :: transpose_helper (xs,ys)
                    | _ -> failwith "The matrix is not a square matrix"
                transpose_helper(xs,ys)
    | _ -> failwith "Incorrectly formatted input"

transpose ([[1;2;3];[2;3;4]]);;

I assume the error is in part due to the empty list, but nothing I do seems to help. Any pointers would be greatly appreciated.

EDIT: This following version of the code, works. Could anyone explain why?

let transpose zs =
    match zs with 
    | [xs;ys] -> 
                let rec transpose_helper (xs, ys) = 
                    match (xs,ys) with
                    | ([],[]) -> []
                    | (x::xs , y::ys) -> [x;y] :: transpose_helper (xs,ys)
                    | _ -> failwith "The matrix is not a square matrix"
                transpose_helper(xs,ys)
    | _ -> failwith "Incorrectly formatted input"

transpose ([[1;2;3];[2;3;4]]);;

val transpose : zs:'a list list -> 'a list list
val it : int list list = [[1; 2]; [2; 3]; [3; 4]]

However, the compiler still complains that the transpose call above should have a unit type unless I bind it using lets. Could anyone please clarify what is going on here?

도움이 되었습니까?

해결책

My guess is you originally wrote this let rec transpose zs = match zs with ... and later changed it to use function instead, which removes the need for the explicit argument. Since zs is still there your function accepts two args which means you're only partially applying it. Since zs is unused its type is unknown making your partially applied function return a generic function value (value restriction). Remove zs and all is well.

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