-3

I'm having a difficult time understanding the concept 'Don't think about How to do but What to do' (Focus on results, not steps) in functional programming. Let's say we have a language that treats functions as first class citizens and no inbuilt functions for iteration (such as forAll in Scala). In that case we first have to create a function that tells how to iterate a given data structure haven't we? So if the language it self does not provide enough functions, then apart from having functions as first class citizens, it would be pretty much same as coding in imperative way wouldn't it?

Please correct me if I'm wrong. Following are the resources that I referred.

Video lecture

Some articles

Prasad Weera
  • 1,223
  • 3
  • 13
  • 25

1 Answers1

2

"How" and "what" are two sides of the same coin, and sometimes it can be useful to think in one way or another. Thinking about "what" to do is a good way to think about recursion, especially for people without much experience writing recursive functions. "How" implies a series of steps, while "what" implies a series of definitions. Let's consider your iteration example (I'm going to use Haskell, since I don't know Scala, but the concepts ought to be directly translatable).

Haskell's iteration function is called map, but suppose we wanted to write it ourselves. If we didn't have much experience with recursion, it might be difficult to imagine how to write a function (map) that applies another function (f) to every element of a list ("mapping" f over list). Here's the type signature of the function we want:

map :: (a -> b) -> [a] -> [b]

So let's try thinking about "what" a function applied to every element of a list is. It is the function applied to the first element, followed by the function mapped over the rest of the list. So let's code that:

map f (firstElement:restOfList) = (f firstElement):(map f restOfList)

Now we're nearly finished. The only thing left is to handle the base case. What if the list is empty? Well clearly any function mapped over an empty list is an empty list, so we'll code that:

map _ [] = []

And we're done! Now if you can think in terms of "how" and write the above code, go right ahead (as I've gained more experience, I tend to do that more often). However thinking in terms of "what" is a useful technique if you find yourself stuck.

Neil Forrester
  • 5,101
  • 29
  • 32