1

I'm new to functional programming and as I'm reading this book. It basically says that if you code contains "var" it means that you're still doing in a imperative way. I'm not sure how do I change my code to be functional way. Please suggests.

So basically what this code does is to processText some text and use regular expression to extract a particular text from "taggedText" and add that to a list and convert the list to json.


    val text = params("text")
    val pattern = """(\w+)/ORGANIZATION""".r

    var list = List[String]()
    val taggedText = processText(text)
    pattern.findAllIn(taggedText).matchData foreach {
      m => list ::= m.group(1)
    }

    pretty(render(list)) // render to json

1 Answer 1

7

Try replacing the middle section with

val list = pattern.findAllIn(taggedText).matchData.map(m => m.group(1)).toList

You can write m => m.group(1) as _.group(1) if you want.

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

2 Comments

As a more general rule, building up a data structure functionally Scala usually turns out to be best done using either "map", "flatMap" or "fold", in increasing order of difficulty. There are a few variants on those ("collect", "groupBy", "foldMap") that may be handy in certain cases, but as a general rule "map", "flatMap" and "fold" get you where you need to go.
If those methods are new to you I recommand yield. You can use a for comprehension and yield the result collection. Behind the scenes yield is translated to map, flatmap, filter and so on.

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.