如何使用'(&lt)'作为变量? [英] How to use '(<)' as a variable?

查看:170
本文介绍了如何使用'(&lt)'作为变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用大于或小于符号作为变量,以便当我输入 Main>时, mySort(<)[1,5,3,6,4,1,3,3,2] Main> mySort(>)[1,5,3,6,4,1,3,3,2] 它会根据我选择的符号将列表从高到低或从低到高排序进入?

解决方案

您可以将(<)并使用它比较每个值。

一个类似的函数

  mySort ::(a  - > a  - >订购) - 比较器功能
- > [a]
- > [a]

Haskell非常聪明,它已经以 sortBy 。这可以让你传递一个返回 Ordering 的函数,它只是

 数据订购= LT | EQ | GT派生(...)

但是你有函数 a - > a - > Bool ,所以你需要把它做成一个订单,然后你可以在 sortBy 中使用它。

  wrap fab |不是$ f a b || f b a = EQ 
| f a b = LT
|否则= GT

现在您可以使用它来包装(<)(>)来解除它与 sortBy

使用b
$ b

  mySort ::(a  - > a  - > Bool) - > [a]  - > [a] 
mySort = sortBy。换行


How would I use the greater or less than sign as a variable so that when I enter Main> mySort (<) [1,5,3,6,4,1,3,3,2] or Main> mySort (>) [1,5,3,6,4,1,3,3,2] it will sort the list from highest to lowest or lowest to highest depending on which sign I chose to enter?

解决方案

You can just pass (<) in and use it compare each value.

A similar function

mySort :: (a -> a -> Ordering) -- Comparator function
       -> [a]
       -> [a]

And Haskell is so smart that this already exists as sortBy. This lets you pass in a function returning an Ordering which is just

data Ordering = LT | EQ | GT deriving(...)

But you have functions a -> a -> Bool so you need to make this into an ordering and then you can use it with sortBy.

wrap f a b | not $ f a b || f b a = EQ
           | f a b                = LT
           | otherwise            = GT

Now you can use this to wrap (<) and (>) to lift it to be used with sortBy

mySort :: (a -> a -> Bool) -> [a] -> [a]
mySort = sortBy . wrap

这篇关于如何使用'(&lt)'作为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆