Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ghc evaluating my infinite list?

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?

like image 632
billt Avatar asked Nov 30 '22 19:11

billt


1 Answers

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.

like image 153
Mark Rushakoff Avatar answered Dec 05 '22 06:12

Mark Rushakoff