Lazy Evaluation

  • + 0 comments

    Your code will be more efficient if you check to see if a number is palindromic before you test to see if it is a prime. Testing for prime quickly becomes more expensive than testing a string .

    You can make your palindrome checker even quicker for large numbers by writing your own function that compares [0] to [-1], [1] to -[2] and so on until you find the first bad match - although that level of performance isn't needed to satisfy the tests on this challenge.

    You can make your code cleaner by creating two lazy enumerators. The first returns an infinite array of palindromic numbers, the second filters the first for prime numbers. Then you just need to take N from the second.

    Note: because find_all and take on lazzy enumerators return lazy enumerators, you don't need to specify lazy for the second enumerator but you will need to convert the lazy enumerator returned by take into an array. Laziness is infectious.

    pals = 1.upto(Float::INFINITY).lazy.find_all {...}
    
    palprimes = pals.find_all {...}
    
    p palprimes.take(n).to_a