1

I'm trying to translate a radix sort algorithm from Java to Haskell, and I'm really new to Haskell. I've been reading tutorials, but they are so lengthy and I'm trying to get my hands dirty now.

I'll be passing a list of lists to the sort algorithm, and my questions are:

  • How would I traverse all elements in a list?
  • How would I access a particular element within a list?

So for instance, I'd need to traverse over every list I have, and access particular elements by index (?) in that particular list. How!?

2
  • 1
    Lists are not arrays. For example, accessing the nth element of a list costs O(n), instead of O(1). If you started with an array in Java then I suggest you use a Vector or Array in Haskell, not a list. OTOH, if this really is homework then the instructor probably does want you using lists. Commented Sep 19, 2011 at 2:02
  • @Thomas thanks, I will keep away from lists Commented Sep 19, 2011 at 14:37

1 Answer 1

4

Since you tagged your question as homework, I'm going to give you a few pointers but no solution. A Haskell book that seems to be particularly beginner friendly is "Learn You a Haskell for Great Good!" (LYAH). You can buy it or read it online for free.

  • Traversing a list requires recursion. See Chapter 5 of LYAH.

  • For accessing a list element by index you can use the !! operator. Note, though, that if you give it an invalid index you get an error. Indexing starts at 0. For a few more standard utility functions on lists, see Chapter 2 of LYAH.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, these are essentially linked lists, so "indexing" a list actually takes time linear in the index. It's usually a terrible idea and really something that should be more heavily discouraged (as should use of head and tail, which I regard as bugs until proven otherwise).