按 haskell 中的元素之一对元组进行排序

Sort tuples by one of their elements in haskell

我有一个这样的列表

[(1,2),(2,1),(3,3)]

我想按第二个元素排序,所以它是:

[(3,3),(1,2),(2,1)]

我试过了

mySort t = sortBy (compare `on` (\(a,b)->b)) t

但是 ghci 显然不识别 sortBy

好的,编辑:

我正在使用 GHCi 编译实际的 .hs 文件,所以我有我的 header:

import Data.List (sortBy)
import Data.Function (on)

module TupleListPolynomial where
type Poly = [(Float,Int)]

如果我这样写,编译器将无法识别 'module'(顺便说一句,使用 :l 和 :r):

[1 of 1] Compiling Main             ( TupleListPolynomial.hs, interpreted )

TupleListPolynomial.hs:5:1: parse error on input ‘module’

如果我翻转它并在下面写入导入,它将无法识别 'import' 并出现相同的错误。

编辑:这样解决了:

module TupleListPolynomial where
import Data.List (sortBy)
import Data.Function (on)
type Poly = [(Float,Int)]

几点观察:

  • 要获得 sortByon,您必须先导入它们
  • 您想按降序排序,一种方法是使用 flip compare 而不是 compare
  • 代替\ (a,b) -> b你也可以使用snd(感谢Arnon)
  • 对于 `on`,您必须使用反引号 ` 而不是 '(感谢 interjay)
  • 不需要mySort t = ... t中的t

一个可能的解决方案:

好的 - 如果你将它放入某个 myPolynomial.hs 文件(或者你想如何称呼它),这个应该编译并加载并工作到 ghci 中:

module TupleListPolynomial where

import Data.List (sortBy)
import Data.Function (on)

type Poly = [(Float,Int)]

mySort :: Ord b => [(a, b)] -> [(a, b)]
mySort = sortBy (flip compare `on` snd)

在 GHCi 中你会写

import Data.List (sortBy)
import Data.Function (on)

let mySort = sortBy (flip compare `on` snd)

事实上,我就是这样测试它的:

测试

> mySort [(1,2),(2,1),(3,3)]
[(3,3),(1,2),(2,1)]