How do I know if a value is higher or lower than another value in a list using recursion?

Asked

Viewed 98 times

4

Being a classified monster with your name, attack and defense. ("medusa", 2, 5) or (string, int, int). And getting a list of monsters, how do I create a function that tells me if the monster I want to evaluate is weaker than the ones on the list, using recursiveness? Example:

maisFraco ("medusa", 2, 5) [("Pegasus", 10, 3),("hidra", 3, 6)]. Return true.
maisFraco ("minotauro", 5, 4) [("grifo", 10, 3),("trol", 3, 6)]. Return false

I think I have to go through the list and compare the values of attack and defense, I think it is using the map, and then I compare until both the values of attack and defense are greater than any on the list, so I can stop my function because the monster is not the weakest (condition of stopping). But I don’t know how to grab the offense and the defense and compare in the list recursively.

maisFraco :: (String, Int, Int) -> [(String, Int, Int)] -> Bool
maisFraco =  

maisFracoAux :: int -> int -> Bool
maisFracoAux x y= if x > y then true else false

tried with an auxiliary function that compares two values to see if they are larger, but I always have the problem of having to compare two numbers

2 answers

4

To make your life easier it would be better to create a guy who represents a Monstro.

So I created the following type:

data Monstro = Status String Int Int
    deriving(Eq, Show) --Obrigatório

For the function you can use guards, this way you compare each element of the list with the element you want to verify is the maisFraco and as it passes you make the comparison with the rest of the list. This can be done as follows:

maisFraco :: Monstro -> [Monstro] -> Bool
maisFraco _ [] = True
maisFraco (Status nome f d) ((Status nl fl dl):xs)
    | f < fl && d < dl = maisFraco (Status nome f d) xs
    | otherwise = False

The moment the Monstro that if you want to compare is stronger in some aspect (force or defense) it already returns False. If every list has been searched and the entry was an empty list it means that it is the Monstro weaker and returns True.

2

By the way another version (this non-recursive).

Considerarei que o monstro M1 é mais fraco que todos  sse 
   não há nenhum M2 tal que 
        M1 possa atacar M2  -- M1.ataque > M2.defesa
        ou 
        M1 consiga defender de M2 -- M1.defesa > M2.ataque  

What in Haskell would be:

mf (_,a,b) ms = not ( any maisfraco ms )
   where maisfraco (_,a1,b1) = a > b1 || b > a1

Note: according to this definition the examples would be both false.

Browser other questions tagged

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