我有一个功能
mytest :: Int -> String
mytest = "Test"
Run Code Online (Sandbox Code Playgroud)
ghci拒绝加载文件:
Couldn't match expected type ‘Int -> String’
with actual type ‘[Char]’
In the expression: "Test"
In an equation for ‘mytest’: mytest = "Test"
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)
添加通配符运算符后,一切正常:
mytest :: Int -> String
mytest _ = "Test"
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么Haskell将第一个解释"Test"为[Char]第二个和第二个String?
String只是一个别名[Char].它的定义如下:
type String = [Char]
Run Code Online (Sandbox Code Playgroud)
一份清单Char构成一份String.
因为类型检查尝试匹配"测试",这是一个你原来的功能没有工作String或[Char]数据类型为Int -> String类型导致类型错误.您可以通过返回Int -> String类型的函数使其工作:
mytest :: Int -> String
mytest = \x -> show x
Run Code Online (Sandbox Code Playgroud)
也可以写成:
mytest :: Int -> String
mytest x = show x
Run Code Online (Sandbox Code Playgroud)
或者像你一样:
mytest :: Int -> String
mytest _ = "Test" -- Return "Test" no matter what the input is
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |