Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort tuples by one of their elements in haskell

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)]
like image 381
dari1495 Avatar asked May 21 '15 17:05

dari1495


1 Answers

A few observations:

  • to get sortBy and on you have to import them first
  • you want to sort in descending order and one way to do this is to use flip compare instead of compare
  • instead of \ (a,b) -> b you can also use snd (thanks Arnon)
  • you have to use back-ticks ` instead of ' for `on` (thanks interjay)
  • the t in mySort t = ... t is not needed

one possible solution:

ok - 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)

in GHCi you would write

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:

test

> mySort [(1,2),(2,1),(3,3)]
[(3,3),(1,2),(2,1)]
like image 63
Random Dev Avatar answered Nov 04 '22 09:11

Random Dev