Guards vs functions with Pattern matching

Asked

Viewed 55 times

3

I’m starting out in Haskell and I was doing some exercises on her Exercism.
When I sent a code, I compared it with the others and came across a very similar one to mine, but I used a definition of Guards (I don’t know if it gets to be Guard, saw in a place calling function by Pattern matching, but without certainty) different:

-- Minha função
transcribe :: Char -> Maybe Char
transcribe nucleotide
    | nucleotide == 'G' = Just 'C'
    | nucleotide == 'C' = Just 'G'
    | nucleotide == 'T' = Just 'A'
    | nucleotide == 'A' = Just 'U'
    | otherwise         = Nothing

-- Função de outro participante
transcribe :: Char -> Maybe Char
transcribe 'G' = Just 'C'
transcribe 'C' = Just 'G'
transcribe 'T' = Just 'A'
transcribe 'A' = Just 'U'
transcribe _   = Nothing

So I would like to understand, is there any difference between the two forms? For cases like this, what is the most correct one? Or the two at the end are the same thing?

1 answer

5


First of all, your job is to use guards (Guards), while that of the other participant uses pattern marriage (patter matching). In addition, both will always have the same results and are semantically equal.

Choosing to write one way or another is a matter of style or to make it easier to read. In this case, as the comparison of each guard is only equality in all cases (nucleotide == ...), the most common is to opt for wedding patterns, even knowing that it makes no difference.

Maybe you want to read a little bit about wedding patterns:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.