As my first haskell program I'm trying to do this - it's the hard way to get 1 to 10. I'm constructing an infinite list of integers, and sorting them, and taking the first 10. My intention was to convince myself that I could work with infinite lists without causing evaluation of them beyond what was strictly (ahem) required for the demanded result.
My code is..
module Main where
import Data.List
minima n xs = take n (sort xs)
main = do
let x = [1..]
print (minima 10 x)
Compiling with ghc and running the resulting executable.. it sits there allocating until killed.
Any hints?
The problem is that you're trying to sort the infinite list. The list can never be fully sorted until all elements in the list are known, so that's why it's hanging. Your program works fine with a finite list.
Also, as a minor aside, you can rewrite minima as
minima n = take n . sort
Because of partial application, minima n
will return a function expecting a list.
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