Reputation: 546
I'm learning Scala by going through books and implementing some standard algorithms in Scala for practice.
I'm trying to find a substring or do exact pattern matching program using brute force method first. I know that I can just use String.substring or iterate through the characters in each string (charAt). But I'm looking for any functional way to find substring (without using built in substring). To be clear, by functional I mean using immutables and avoiding manual iteration etc.
Upvotes: 2
Views: 392
Reputation: 6533
You're asking a very broad question, so I'll provide some tips to help you get started on your exercise. There are a myriad of ways to tackle this, and I'm sure the more experienced functional programmers will probably help even more. :)
First take your string, get the characters, and convert it into a list. Taken from the Scala console:
scala> val str = "This string is just an example."
str: String = This string is just an example.
scala> val list = str.toCharArray.toList
res15: List[Char] = List(T, h, i, s, , s, t, r, i, n, g, , i, s, , j, u, s, t, , a, n, , e, x, a, m, p, l, e, .)
An Array
is mutable (see Array Scaladoc), but a List
is immutable (see List Scaladoc). Now you can start doing functional stuff on it. :)
Scala collections have a huge number of operations you can perform. Some that I find most useful as an imperative programmer trying to unlearn bad habits are map
, reduce
, and fold
. For some tips on using them, check out my blog post Map, reduce, and fold for the programmatically imperative
Upvotes: 3