Process the same input file concurrently Let's say we have a text file that contains 2 different types of lines. For the sake of example, one group starts with "i:" (for Integer) and the other group starts with "s:" (for String), something like the following file: s:New york s:Apple i:387548 s:Amsterdam i:4556 i:39874 s:Orange i:56787 s:Banana i:4657567 s:Turkey i:45679456 s:Iran i:4356456 i:23423 i:456 s:Ukraine i:453645 i:5456 We want to process these input lines separately but concurrently. And the process can be anything, for this example, we just print them to the console. But what matters is that we open the file only for READ so 2 different processes (or routines) can read the file at the same time. The Cats Effect answer to open files (or in general any resources) in a safe and efficient way, is Resource class. So we need a function to take the path to the file and give us a Resource of some type that allows us to read the file line by line. One o...
Another String search problem that we like to solve in a functional way. This problem is very similar to the previous one, Functional algorithm to find the position of a sub-string in a string, but it is a bit easier in the sense that we can always return an Int, so we do not have to return an Option of Int, because the number of the occurrences of a String in another String is always a non-negative number.
So the signature of the function that we want to write looks like this:
def countSubstring(str: String, subString: String): Int = ???⚠️ Be careful about overthinking the problems and always remain within the scope, in this case, it is very easy to overthink this problem by mixing up the terms sub-string and word. We only care about sub-strings and our algorithm does not know about words, meaning that our function should return the number 3 (and not 2) if we pass it the following parameter:
"This book is the best book among my books", "book"
As we saw in the previous post, we implement loops using recursion in functional programming. So we need a nested function to be called recursively that:
- Takes 3 parameters, 2 Strings, and one Int
- If the first String is smaller than the second String, it returns the Int parameter, otherwise
- If the First String starts with the second String, make the recursive call with
- The first String without its first character
- The original second String
- The Int param + 1
def countSubstring(str: String, subString: String): Int = {
def loop(remainder: String, lookingFor: String, count: Int): Int = {
if (remainder.length < lookingFor.length)
count
else if (remainder.substring(0, lookingFor.length) == lookingFor)
loop(remainder.substring(lookingFor.length), lookingFor, count + 1)
else
loop(remainder.substring(1), lookingFor, count)
}
loop(str, subString, 0)
}
Comments
Post a Comment