Bercovici Adrian
Bercovici Adrian

Reputation: 9360

Pattern matching on wild card

Hello i am trying to pattern match for a wild card pattern but I need to "grab" the wild card.I am trying to parse a String to a list of Maybe Int.

INPUT
{123,aa,55,66}
OUTPUT
[Just 123,Nothing,Just 55.4,Just 66.3]

So I put together the following method:

Method

readDataRaw::String->[Maybe Int]
    readDataRaw (x:xs)=go [] [](x:xs) where
            go _ ls []         = ls
            go small big (x:xs)= case x of
                                  '}'    -> big
                                  ','    -> go [] ((readMaybe small::Maybe Int):big)  xs 
                                   c@(_) -> go [] c:small big xs

Error

parse error on input `->'
   |
66 |                                    c@(_) -> go [] c:small big xs
   |                                          ^^

How can i use the wild card on the right side of the -> in my last case ?

Upvotes: 1

Views: 707

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can just use a variable identifier, a variable does not specify any pattern, so you can write it like:

readDataRaw::String -> [Maybe Int]
readDataRaw (x:xs) = go [] [](x:xs) where
    go _ ls [] = ls
    go small big (x:xs) = case x of
        '}' -> big
        ',' -> go [] ((readMaybe small::Maybe Int):big)  xs 
        c -> go [] c:small big xs

The above however has some errors, and incomplete patterns. For example in readDataRaw you only specify the (x:xs) pattern in the head, whereas it is - strictly speaking - possible that you call the function with an empty list []. It also "clashes" with the (x:xs) in the go pattern: this is not a problem since Haskell takes the "closest" variable, so the one defined in th3e go clause, but it introduces some confusion. In the last case (with the c, you als return go [] c : small big xs, which will be interpreted as (go [] c) : small big xs which does not make much sense. A "refactored" implementation could look like:

readDataRaw::String -> [Maybe Int]
readDataRaw = go [] [] where
    go _ ls [] = ls
    go small big (x:xs) = case x of
        '}' -> big
        ',' -> go [] ((readMaybe small::Maybe Int):big)  xs 
        c -> go (c:small) big xs

But still, it is a bit "ugly". This is partly because it is unclear what you want to do.

Upvotes: 4

Related Questions