Sorting in haskell with parameter using higher order function

前端 未结 1 849
礼貌的吻别
礼貌的吻别 2021-01-24 11:50

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条回答
  • 2021-01-24 12:06

    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 = ...
    
    0 讨论(0)
提交回复
热议问题