Posts

Showing posts with the label Functional Programming

Can Std::transform Be Replaced By Std::accumulate?

Answer : Those two algorithms have completely different purpose. std::accumulate is known as fold in functional programming world, and it's purpose is iterate over elements of a sequence and apply two-argument folding operation to those elements, with one argument being result of previous fold and other being element of the sequence. It naturally returns the a single result - a fold of all elements of a sequence into one value. On the other hand, std::transform copies values from one sequence to another, applying a unary operation to each element. It returns an iterator to the end of sequence. The fact that you can supply any code as the fold operation allows us to use std::accumulate as a generic loop replacement, including an option to copy values into some other container, but that it is ill-advised, as the whole reason for introducing those (rather simple) algorithms was to make programs more explicit. Making one algo to perform the task which is normally associat...

Best Way To Represent A Readline Loop In Scala?

Answer : How about this? val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null).mkString Well, in Scala you can actually say: val lines = scala.io.Source.fromFile("file.txt").mkString But this is just a library sugar. See Read entire file in Scala? for other possiblities. What you are actually asking is how to apply functional paradigm to this problem. Here is a hint: Source.fromFile("file.txt").getLines().foreach {println} Do you get the idea behind this? foreach line in the file execute println function. BTW don't worry, getLines() returns an iterator, not the whole file. Now something more serious: lines filter {_.startsWith("ab")} map {_.toUpperCase} foreach {println} See the idea? Take lines (it can be an array, list, set, iterator, whatever that can be filtered and which contains an items having startsWith method) and filter taking only the items starting with "ab" . Now take every item and map ...