Task:
Write a recursive Haskell function, which get 2 ordered list and the function decide that each of them element are equal or not (if one of them are same the function value is
False
).For example:
myfunction [1..5] [6..10] == True
myfunction [1..5] [5..10] == False
I cannot use the elem
function. I can use recursion and case apart choice.
Function type:
myfunction :: Ord a => [a] -> [a] -> Bool
I tried something like this:
myfunction :: Ord a => [a] -> [a] -> Bool
myfunction [] list = True
myfunction list [] = True
myfunction (x:xs) (y:ys)
| x == y = False
| xs == myfunction ???????? = False
But it does not works...
(This answer is really just the comments you already received in answer form.) You'd implement it as follows:
myFunction [] _ = True
myFunction _ [] = True
myFunction (x : xs) (y : ys) = case compare x y of
LT -> myFunction xs (y : ys)
EQ -> False
GT -> myFunction (x : xs) ys
This works because if x
is smaller than y
, x
is also smaller (and therefore not equal, which is what we really wanted to know) than any element in ys
. That means we can ignore it and check the rest of the lists. When x
is greater than y
, it's the other way around.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.