Saturday 4 June 2016

Haskell: Find k least values in unsorted list


listUtil.hs
import Data.List

getLeastValues :: Int -> [Integer] -> [Integer]
getLeastValues k xs = take k (sort xs)

*Main> :load listUtil.hs
[1 of 1] Compiling Main             ( listUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getLeastValues 4 [2, 200, 12, 3, 4, 5, 123, 43, 21, -19]
[-19,2,3,4]
*Main> 
*Main> getLeastValues 40 [2, 200, 12, 3, 4, 5, 123, 43, 21, -19]
[-19,2,3,4,5,12,21,43,123,200]
*Main>


Previous                                                 Next                                                 Home

No comments:

Post a Comment