Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join strings with XML node between in scala

Tags:

xml

scala

I have a list of strings and I need to join them together with <br/> tags in between. So starting from:

val list = List("line1", "line2", "line3")

I need to end up with a NodeSeq of:

line1<br/>line2<br/>line3

It's possible the list contains only one element, in which case I should end up with a NodeSeq just of Text("line1").

Is there a one-liner to do this, using one of the higher order functions on list? I've tried to play around with foldLeft but can't seem to get it to do what I want.

like image 558
user1106210 Avatar asked Dec 19 '11 15:12

user1106210


2 Answers

list.map(scala.xml.Text(_):scala.xml.NodeSeq).reduce(_ ++ <br /> ++ _)

Note that we have to widen the type to scala.xml.NodeSeq manually as Text is too restrictive for the reduce method. The more concise

list.map(scala.xml.Text).reduce(_ ++ <br /> ++ _)

won’t compile.

like image 177
Debilski Avatar answered Nov 13 '22 22:11

Debilski


If you don't mind using Scalaz, there's intersperse:

import scalaz._
import Scalaz._

list.map(xml.Text(_): xml.Node).intersperse(<br/>): xml.NodeSeq
like image 3
Travis Brown Avatar answered Nov 13 '22 23:11

Travis Brown