List F#函数参数类型不匹配
我使用下面的函数来生成F中两个列表的元组# 当调用包含整数列表的函数时,如List F#函数参数类型不匹配,list,function,f#,List,Function,F#,我使用下面的函数来生成F中两个列表的元组# 当调用包含整数列表的函数时,如 System.Console.WriteLine( MyOwnZipper [1; 2; 3] [4; 5; 6] ) 当我将参数更改为字符串时,问题就出现了 System.Console.WriteLine( MyOwnZipper [1; 2; 3] ["Hello"; "World"; "Peace"] ) 我得到以下错误 error FS0001: This expression was expected
System.Console.WriteLine( MyOwnZipper [1; 2; 3] [4; 5; 6] )
当我将参数更改为字符串时,问题就出现了
System.Console.WriteLine( MyOwnZipper [1; 2; 3] ["Hello"; "World"; "Peace"] )
我得到以下错误
error FS0001: This expression was expected to have type
int
but here has type
string
exit status 1
出现这种情况的原因是
匹配表达式的第一种情况:
| [],l| l,[] -> []
这里,标识符l
被绑定到第一个列表或第二个列表。由于标识符不能同时具有两种不同的类型,编译器得出结论,列表必须具有相同的类型。因此,如果您尝试使用不同类型的列表调用函数,您会得到一个类型不匹配错误,这是意料之中的
要解决此问题,请将案例分为两种情况:
let rec MyOwnZipper xs ys =
match xs,ys with
| [],l -> []
| l,[] -> []
| x1::rest, y1::yrest -> (x1, y1) :: (MyOwnZipper rest yrest)
非常感谢你的解释。它解决了我的问题!
let rec MyOwnZipper xs ys =
match xs,ys with
| [],l -> []
| l,[] -> []
| x1::rest, y1::yrest -> (x1, y1) :: (MyOwnZipper rest yrest)