Home > Net >  Haskell giving index for the items in list
Haskell giving index for the items in list

Time:11-18

In a function I should number the elements of a list, which should return like this: "n: rest of the string"

numberLines :: [String] -> [String]

["asd  qwe", "-- Foo", "", "\thello world "] 
   -> ["1: asd  qwe", "2: -- Foo", "3: ", "4: \thello world "]

I'm not allowed to use simple recursion, only higher order functions (if needed)

My problems:

  1. I don't know how to make the counter
  2. I don't know how to put an Int in front of the string ("counter: " "string" will not work)

CodePudding user response:

You can work with zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] that will concurrently enumerate through two lists and produce a list of items where ci is f ai bi for c = zipWith f a b. As first item you can for example feed it an infinite list [1..] and as second the list of lines, so:

numberLines :: [String] -> [String]
numberLines = zipWith f [1..]
    where f idx st = …

where you still need to fill in the parts.

CodePudding user response:

A lot of people want you to use zipWith. While this will give the right answer, it consumes two lists, and so doesn't fully support list fusion, which can only work on one list at a time. Here's an alternative solution that can fully fuse:

numberLines :: [String] -> [String]
numberLines xs = foldr (\st acc idx -> …:acc (idx 1)) mempty xs 1

As in Willem Van Onsem's answer, you'll need to fill in the part yourself.

  • Related