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. 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:
[(s,f)]
part is not a pattern for a list: you would regularly use a variable name, or a pattern. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.