Akos Fajszi
Akos Fajszi

Reputation: 83

Number each list element and format text in haskell

I want to give each one a number from 1 to length(x:xs), like a book's page number. Unfortunately it only works backwards.

numberL :: [String] -> [String]
numberL [] = []
numberL (x:xs) = ([show (length(x:xs)) ++ ": " ++ x] ++ numberL (xs))

Also how do I remove any new line and tab from the text and replace it with the actual new line and tabulator?

Upvotes: 1

Views: 210

Answers (2)

Stephane Rolland
Stephane Rolland

Reputation: 39926

There are multiple built-in Haskell functions in Prelude that are good to learn and use them. zip and zipWith are two of them, when you think about something to be done using two different lists into one result list:

[1..] will generate the list of indices for you, it's an infinite list

appendIndex :: String -> Int -> String
appendIndex s i = (show i) ++ " :" ++ s

indexThem :: [String] -> [String] 
indexThem l = zipWith appendIndex l [1..]

if you wanted to use zip, which is more basic but a little more verbose:

appendIndex :: (String,Int) -> String
appendIndex (s,i) = (show i) ++ " :" ++ s

indexThem :: [String] -> [String] 
indexThem l = fmap appendIndex $ zip l [1..]  
-- if you dont know about Functors yet, `fmap` is the generic way of doing `map` 

Upvotes: 3

To get it right, it's important to understand why you're thinking wrong. Your recursion looks like this:

numberL (x:xs) = ... ++ numberL xs

So you calculate numberL xs and then put something in front of it. If numberL xs were correct, then then it would be numbered from 1 onwards, like: 1:..., 2:..., 3:.... So you could never build numberL (x:xs) from numberL xs just by adding new elements at the front. The whole numbering would be wrong. Instead you'd have to change the whole numbering of numberL xs.

The problem therefore is that it's not very useful to know numberL xs in order to calculate numberL (x:xs), due to the fact numberL always starts numbering from 1.

So lift that restriction. Build a function that numbers starting at n,

numberLFrom :: Int -> [String] -> [String]
numberLFrom n []     = ...
numberLFrom n (x:xs) = ...

Now the question you have to ask yourself is, in order to number (x:xs) starting at n you need to number xs starting at which number? And then how do you introduced the numbered x to that result?

Upvotes: 3

Related Questions