Sorting in haskell with parameter using higher order function

丶灬走出姿态 提交于 2019-12-02 13:16:46

问题


Hi I'm a Haskell beginner and I'm really lost. This is for my assignment, and it asks me to do something like below using higer order function

Main> mySort (<) [1,5,3,6,4,1,3,3,2] 
[1,1,2,3,3,3,4,5,6] 
Main> mySort (>) [1,5,3,6,4,1,3,3,2] 
[6,5,4,3,3,3,2,1,1] 
Main> mySort longerWord [“Hello”, “The”, “a”, “Daniel”, “Declarative”]
[“Declarative”, “Daniel”, “Hello”, “The”, “a”]

First of all, I thought I should make a function that distinguish whether it's < , > or longerWord

checkConditionStr::String->Int
checkConditionStr str
    |str=="(<)" =1
    |str=="(>)" =2
    |str=="longerWord" =3

but the example doesn't have quotation mark (i.e. mysort (<) not my sort"(<)" so here is my first problem. I worte this function but it's not compiling. otherwise is for longerWord

checkCondition::Ordering->Int
checkCondition ord
    |ord==(<) =1
    |ord==(>) =2
    |otherwise =2

secondly I still have difficulty understanding higher order function. would this make sense?

mySort::(String->Int)->[a]->[a]
mySort i list
    |i==1 map (sortBy compare) list
    |i==2 map (sortBy(flip compare)) list

回答1:


You're not supposed to match against those functions specifically. It defeats the purpose of using a higher-order function in the first place. In fact, you can't write it like this, since there is no general way of comparing functions.

Instead, use the passed function directly for the sorting. That way, it will work for any suitable comparison function, not just the ones you've explicitly written code for.

For example, imagine the task was to combine two values using a passed operator:

combine (+) 2 3 = 5
combine (*) 3 5 = 15
combine max 10 100 = 100

You would solve it like this:

combine op x y = x `op` y

Can you use a similar approach to solving the sorting problem?

Hint: You may want to define a helper function to transform the passed comparison function into a form suitable for sortBy:

compareUsing :: (a -> a -> Bool) -> (a -> a -> Ordering)
compareUsing op x y = ...


来源:https://stackoverflow.com/questions/16101710/sorting-in-haskell-with-parameter-using-higher-order-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!