简体   繁体   中英

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. 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:

  1. the guard options are not exhaustive: what happens when x is not equal to s?
  2. the [(s,f)] part is not a pattern for a list: you would regularly use a variable name, or a pattern.
  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?

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.

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