I'm just working through http://www.yqcomputer.com/

nice, and wanted to expand on one of the examples in the chapter on

higher order functions when I hit a snag.

The example is:

chain :: (Integral a) => a -> [a]

chain 1 = [1]

chain n

| even n = n:chain (n `div` 2)

| odd n = n:chain (n*3 + 1)

numLongChains :: Int

numLongChains = length (filter isLong (map chain [1..100]))

where isLong xs = length xs > 15

which gets me a list of numbers (a 'chain') for examining

http://www.yqcomputer.com/

such chains of at least a given length there are in a range. So far so

good.

I then wanted to know how long the longest chain in a given range

would be. Hey, no problem.

longestChainLength :: Int -> Int

longestChainLength x = maximum (map length (map chain [1..x]))

is what I came up with, and though it does take some time for x >

100000 (recursion takes its toll), it works, and I understand what it

does.

But how do I get not the length of the longest chain, but the actual

longest chain?

Probably just haven't been exposed to Haskell long enough, but I can't

seem to get my head around a solution - any pointers appreciated.

-- Christopher

Data.List.maximumBy:

maximumBy :: (a -> a -> Ordering) -> [a] -> a

in conjunction with Data.Ord.comparing:

comparing :: Ord a => (b -> a) -> b -> b -> Ordering

gives:

longestChainLength = maximumBy (comparing length)

1. Filter longest lists in list help

2. List of lists of lists of lists...

3. Sort a List, in a List of Lists of Lists

4. list/sequence problem: a 'keep' list to a list of 'kept' lists

5. Compare List A to List B, Return List B Items Not in List A

6. common elements between list of lists and lists

7. Lists within Lists or Nested Linked Lists...

8. Extracting a List from a List of lists

9. consing a list-of-numbers to a list-of-lists-of-numbers

10. list of ascii to list of chars, and list question

11. convert list of lists to list

12. Duplicating list of lists [newbie]

13. (newbie) N-uples from list of lists

14. list of lists of lists ....

15. Comparing List A to List B and add what's missing from List B

2 post • Page:**1** of **1**