在Haskell中以指定的顺序插入

时间:2016-05-17 10:34:02

标签: haskell insertion-sort

我正在尝试在haskell中为我的每周大学作业实施插入排序。这是我的插入和排序功能:

  insert :: (Ord a) => a -> [a] -> [a]
  insert a [] = [a]
  insert a (a':as)
       | a <= a'   = a:a':as
       | otherwise = a':insert a as


  insertionSort :: (Ord a) => [a] -> [a]
  insertionSort   []      = []
  insertionSort (a:as) = insert a (insertionSort as)

这有效,但我的导师指定了这样的签名:

insert :: (a -> a -> Bool) -> a -> [a] -> [a]
insertionSort :: (a -> a -> Bool) -> [a] -> [a]

我现在尝试的所有内容都失败了,编译器错误也没有用。希望你们能帮助我!

编辑:

我的导师给出的例子如下:

Main> insert (<) 3 [1,2,5,7,9]
[1,2,3,5,7,9]
Main> insSort (>) [7,9,1,2,5]
[9,7,5,2,1]

1 个答案:

答案 0 :(得分:2)

您需要做的就是使用布尔函数参数的结果而不是固定的比较,如下所示:

insert :: (Ord a) => (a -> a -> Bool) -> a -> [a] -> [a]
insert _ a [] = [a]
insert f a (a':as)
     | f a a'   = a:a':as
     | otherwise = a':insert f a as

与其他功能类似。

insertionSort :: (Ord a) => (a -> a -> Bool) -> [a] -> [a]
insertionSort _  []      = []
insertionSort f (a:as) = insert f a (insertionSort f as) 

Demo