I have a list like this
[(1,2),(2,1),(3,3)]
And I want to sort it by the second element, so it'd be:
[(3,3),(1,2),(2,1)]
I've tried
mySort t = sortBy (compare `on` (\(a,b)->b)) t
But ghci does not recognice sortBy apparently
Okay, editing:
I'm using GHCi to compile actual .hs files, so i've got my header:
import Data.List (sortBy)
import Data.Function (on)
module TupleListPolynomial where
type Poly = [(Float,Int)]
And if I write it like this, the compiler won't recognize 'module'(using :l and :r btw) :
[1 of 1] Compiling Main ( TupleListPolynomial.hs, interpreted )
TupleListPolynomial.hs:5:1: parse error on input ‘module’
And if I flip it and write the imports below it won't recognize 'import' with the same error.
EDIT: Solved by putting it like this:
module TupleListPolynomial where
import Data.List (sortBy)
import Data.Function (on)
type Poly = [(Float,Int)]
A few observations:
sortBy
and on
you have to import them firstflip compare
instead of compare
\ (a,b) -> b
you can also use snd
(thanks Arnon)`
instead of '
for `on`
(thanks interjay)t
in mySort t = ... t
is not neededok - this one should compile and also load and works into ghci if you put it into some myPolynomial.hs
file (or however you want to call it):
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)
import Data.List (sortBy)
import Data.Function (on)
let mySort = sortBy (flip compare `on` snd)
indeed this is what I did to test it like this:
> mySort [(1,2),(2,1),(3,3)]
[(3,3),(1,2),(2,1)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With