Home > database >  Haskell - Couldn't match type
Haskell - Couldn't match type

Time:03-18

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?

CodePudding user response:

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.

  • Related