简体   繁体   English

F#函数参数类型不匹配

[英]F# function argument type mismatch

I am using following function to make tuples of two lists in F# 我正在使用以下函数在F#中创建两个列表的元组

let rec MyOwnZipper xs ys =
    match xs,ys with
    | [],l| l,[]  -> []
    | x1::rest, y1::yrest -> (x1, y1) :: (MyOwnZipper rest yrest) 

it works fine when calling function with lists of integers like 当调用带有整数列表的函数时,它工作正常

System.Console.WriteLine( MyOwnZipper [1; 2; 3] [4; 5; 6] )

The problem comes when I change arguments to string 当我将参数更改为字符串时出现问题

 System.Console.WriteLine( MyOwnZipper [1; 2; 3] ["Hello"; "World"; "Peace"] )

I get the following error 我收到以下错误

 error FS0001: This expression was expected to have type
    int    
but here has type
    string    

exit status 1

This happens because of the first case of the match expression: 发生这种情况是由于match表达式的第一种情况:

       | [],l| l,[]  -> []

Here, the identifier l gets bound either to the first list, or to the second list. 在此,标识符l被绑定到第一列表或第二列表。 Since an identifier cannot have two different types at once, the compiler concludes that the lists must have the same type. 由于标识符不能一次具有两种不同的类型,因此编译器得出结论,列表必须具有相同的类型。 Therefore, if you try to call the function with differently typed lists, you get a type mismatch error, quite expectedly. 因此,如果尝试使用不同类型的列表调用该函数,则很可能会收到类型不匹配错误。

To fix the problem, break the case in two separate cases: 要解决此问题,请在两种情况下分开进行处理:

let rec MyOwnZipper xs ys =
    match xs,ys with
    | [],l  -> []
    | l,[]  -> []
    | x1::rest, y1::yrest -> (x1, y1) :: (MyOwnZipper rest yrest) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM