1
maiores :: Int -> [Int] -> Int
maiores _ [] = 0
maiores n (x:xs)
someone has some idea of how to do?
1
maiores :: Int -> [Int] -> Int
maiores _ [] = 0
maiores n (x:xs)
someone has some idea of how to do?
2
There are several ways to do, in addition to the aforementioned solution using guards.
Filtering those larger than n and then counting the number of elements
List comprehension:
maiores :: Int -> [Int] -> Int
maiores n xs = length [x | x<-xs, x > n]
Filter:
maiores :: Int -> [Int] -> Int
maiores n xs = length $ filter (>n) xs
Or you can make a recursive solution with Ifs (much like the solution that uses guards):
maiores :: Int -> [Int] -> Int
maiores _ [] = 0
maiores n (x:xs) =
if x > n
then 1 + maiores n xs
else maiores n xs
1
To solve this problem you need to use guards, this way you can test a condition.
As Haskell is a purely functional language the ideal is to use recursion.
Being (x:xs)
the entire list where x
is the first element and xs
is the rest of the list, you need to compare if the first element is larger than n
if it is you will add 1
to return the function result to the rest of the list, if not you just need to call the function recursively without adding anything to the return.
Remembering that it is possible to make this sum to the return of the function, because its return is also Int
Full function:
maiores :: Int -> [Int] -> Int
maiores _ [] = 0
maiores n (x:xs)
| x > n = 1 + maiores n xs
| otherwise = maiores n xs
Browser other questions tagged haskell
You are not signed in. Login or sign up in order to post.
Good! By the way a little weirder:
maiores n=length . filter (>n)
– JJoao