Question

I am trying to return the second element of a tuple that has the same first element as the char.

If there isn't a tuple with same char as it's first element then I want to return 0

There can only be 0 or 1 tuples with the same char as the char given, hence taking the head of the [Int] returned by the list comprehension.

this is the code I wrote, the error is when I try to check whether a tuple (c,) is in the list of tuples with 'elem (c,) m'

type Mem = [(Name,Int)]

getVal :: Char -> Mem -> Int
getVal c m
        | elem (c,_) m = head [snd n | n <- m, fst n == c]
        | otherwise = 0

A fix for that problem, or a suggestion of a better way to do this would be recieved gratefully!

Thanks

Was it helpful?

Solution 3

elem (c,_) is not a valid haskell expression, because _ can only be used in a pattern (and not in a value). You almost have the solution with head [snd n | n <- m, fst n == c]. You should first evaluate it, and check what is inside. It will be simpler and safer.

I would use something like

getVal :: Char -> Mem -> Int
getVal c m = case [snd n | n <- m, fst n == c] of
    [] -> 0
    x:_ -> x

OTHER TIPS

It's very simple, if you know the Prelude well.

import Data.Maybe (fromMaybe)

getVal :: Char -> Mem -> Int
getVal c = fromMaybe 0 . lookup c

You can use find:

import Data.List

getVal :: Char -> Mem -> Int
getVal c = maybe 0 snd . find ((==)c) . fst) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top