[英]Haskell - Couldn't match type
I am trying to write a function in Haskell that takes as input a String and a list with the pattern [(String, Float)] and output the Float assigned to the key String that matches my input, but I don't understand what am I doing wrong.我正在尝试在 Haskell 中编写一个 function,它将一个字符串和一个带有模式 [(String, Float)] 的列表和 output 分配给与我的输入匹配的键字符串的浮点数作为输入,但我不明白这是什么我做错了。 This is my code:这是我的代码:
a = [("x",1.21),("y",3.52),("z",6.72)]
val :: String -> [(String, Float)] -> Float
val x [(s,f)]
| x == s = f
And it gives me the error它给了我错误
* Couldn't match type `Double' with `Float'
Expected type: [(String, Float)]
Actual type: [([Char], Double)]
* In the second argument of `val', namely `a'
In the expression: val "x" a
In an equation for `it': it = val "x" a
Could anyone explain what am I doing wrong and how does this type mismatch make sense?谁能解释我做错了什么以及这种类型不匹配有何意义?
There are a few problems in the definition of val
, not in the type signature:在val
的定义中有一些问题,而不是在类型签名中:
[(s,f)]
part is not a pattern for a list: you would regularly use a variable name, or a pattern. [(s,f)]
部分不是列表的模式:您会经常使用变量名或模式。Consider this solution throwing an error:``考虑这个解决方案抛出一个错误:``
val :: String -> [(String, Float)] -> Float
val x [] = error ("Not Found: " ++ show x)
val x ((s,f):rest) | s==x = f
| otherwise = val x rest
You could also return Just f
and Nothing
if you use Maybes.如果您使用 Maybes,您也可以返回Just f
和Nothing
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.