简体   繁体   English

Haskell - 无法匹配类型

[英]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的定义中有一些问题,而不是在类型签名中:

  1. the guard options are not exhaustive: what happens when x is not equal to s?保护选项并不详尽:当 x 不等于 s 时会发生什么?
  2. the [(s,f)] part is not a pattern for a list: you would regularly use a variable name, or a pattern. [(s,f)]部分不是列表的模式:您会经常使用变量名或模式。
  3. What happens if after traversing the whole list you don't find a match?如果在遍历整个列表后没有找到匹配项会怎样? Do you throw an error, or a Maybe, or return a sensible default value?你会抛出一个错误,或者一个 Maybe,或者返回一个合理的默认值吗?

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 fNothing

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

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