merge :: [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge (x:xs) (y:ys) = x : y : merge xs ys
I have got this working but now I need to sort them in ascending order.
You just need to compare x
and y
and decide which to add to the result first. Note that you only add one at a time; the next element after x
might still come before y
.
Note you need the Ord
constraint to ensure that <=
is defined for a
.
merge :: Ord a => [a] -> [a] -> [a]
merge xs [] = xs
merge [] ys = ys
merge xs@(x:xs') ys@(y:ys') | x <= y = x : merge xs' ys
| otherwise = y : merge xs ys'
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.