How can i make Insert_sort high-order-function in Haskell -
plz watch code
insert x [] = [x] insert x (y:ys) | x < y = x:y:ys | x == y = y:ys ++ [x] | otherwise = y:insert x ys insert_sort [] = [] insert_sort (x:xs) = insert x (insert_sort xs) insert_pair (x,y) [] = [(x,y)] insert_pair (x,y) ((a,b):yd) | x > = (a,b):insert_pair (x,y) yd | otherwise = (x,y):(a,b):yd insert_sort_pair [] = [] insert_sort_pair (x:xs) = insert_pair x (insert_sort_pair xs) insert_high f [] = [] insert_high f (x:y:ys) | f x y = x:y:ys | otherwise = y:insert x ys insert_high f ((a,b):(c,d):yd) | f c = (a,b):insert_pair (c,d) yd | otherwise = (a,b):(c,d):yd insert_sort_high f [] = [] insert_sort_high f (x:xs) = insert_high (f) x (insert_sort_high (f) xs) i want make insert_sort-high can both insert_sort , insert_pair_sort. "insert_sort_pair" compare number in (number,symbol). example:
insert_sort_high (<) [3,5,2,1,4] -> [1,2,3,4,5] insert_sort_high (>) [(2,'a'),(3,'b'),(1,'c')] -> [(1,'c'),(2,'a'),(3,'b')] but, doesn't work... how can fix it?
first, fundamental misunderstanding.
write type insert_high - should (a -> -> bool) -> [a] -> [a]. you've written specialization lists of tuples, you've forced less general that.
you can cover general case. you're being misled examples.
i'd argue want is
λ insert_sort_high (<) [3,5,2,1,4] [1,2,3,4,5] λ insert_sort_high (\(x,y) (a,b) -> x < a) [(2,'a'), (3,'b'), (1,'c')] [(1,'c'),(2,'a'),(3,'b')] the latter can written little more as
λ :m +data.function λ insert_sort_high ((<) `on` fst) [(2,'a'), (3,'b'), (1,'c')] [(1,'c'),(2,'a'),(3,'b')] of course, that's if want sorting on first element of pair.
λ insert_sort_high ((<) `on` fst) [(2,'a'), (3,'b'), (1, 'a'), (1,'b'), (1,'c'), (1,'a')] [(1,'a'),(1,'c'),(1,'b'),(1,'a'),(2,'a'),(3,'b')] if want sort entire pair, can too
λ (1,'a') < (1,'b') true λ (1,'z') < (2,'a') true λ insert_sort_high (<) [(2,'a'), (3,'b'), (1,'a'),(1,'b'),(1,'c'), (1,'a')] [(1,'a'),(1,'a'),(1,'b'),(1,'c'),(2,'a'),(3,'b')] but digress.
with in mind need delete tuple case, , clean typos.
insert_high :: (a -> -> bool) -> -> [a] -> [a] insert_high _ x [] = [x] insert_high f x (y:ys) | f x y = x:y:ys | otherwise = y : insert_high f x ys insert_sort_high _ [] = [] insert_sort_high f (x:xs) = insert_high f x (insert_sort_high f xs)
Comments
Post a Comment