0

So I have to number each string in list of strings

Like this:

numberLines ["one", "two", "three"] 
   ==> ["1: one", "2: two", "3: three"]

I tried this:

numberLines = map (\g -> (x + 1) : g) where
 x = 0

but of course it didn't work

2
  • You can work with zipWith. Commented Nov 24, 2020 at 22:23
  • you should be able to fix your attempt with mapAccumL. Commented Nov 24, 2020 at 23:44

2 Answers 2

1

In Haskell variables are immutable, so you can not change the value of a variable like in an imperative language like Python.

You can for example use zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] to zip the list of strings together with a list of Ints:

numberLines :: [String] -> [String]
numberLines = zipWith f [1 :: Int .. ]
    where f i s = show i ++ ' ' : ':' : s

Here f thus takes an Int and a String and produces a string "i: s" with i the string representation of the number, and s the string.

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

Comments

1

Others suggested you try using zipWith or mapAccumL to implement the function. Here are two implementations using those functions:

addNumber n string = show n ++ ": " ++ string

numberLines = snd . mapAccumL (\n string -> (n + 1, addNumber n string)) 1

numberLines1 = zipWith addNumber [1..]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.