0

I'm starting with Scala and now I am talking about higher order functions but I am having a hard time dealing with this way of programming using functions as inputs.

I must code a higher order function using only fold, scan and/or reduce that concatenates a string like so:

concatenate(List("S", "T", "R", " example!") , f) //> res1: List[String] = List(STR example!, TR example!, R example!, " example!", "") 

Does anyone know how can I approach this problem?

1 Answer 1

5

Use scan only:

List("S", "T", "R", " example!").reverse.scan("")((x, y) => y + x).reverse // res72: List[String] = List(STR example!, TR example!, R example!, " example!", "") 

Use scanRight:

List("S", "T", "R", " example!").scanRight("")(_+_) // res73: List[String] = List(STR example!, TR example!, R example!, " example!", "") 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! Can you just explain to me what does this do: "(x, y) => y + x" ?
It's used to guarantee the paste order of left + right, notice the list is reversed initially, if using x + y, then you will end up with example! RTS instead of the order you wanted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.