DEV Community

Discussion on: Which types of loops are most popular in the programming languages you use?

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

F# has some traditional looping constructs like for and while. However, they provide functions that take all the common plumbing out of looping. For example, say you want to loop through a list of items and convert each one to a string. You only have to define how to do it for one item.

let stringify item =
    sprintf "%s x%i" item.Name item.Quantity

// stringify {Name="Confabulator"; Quantity=11} = "Confabulator x11"

Then you use a List operation to perform that transformation on a whole list. Without having to worry about the mechanics of looping through it.

let items = [ ... ]
let strings = List.map stringify items

I really like the separation of concerns. My stringify function only worries about a single item... it doesn't know anything about lists. And since List introduces the need to loop, it also provide functions to do that for you (map, filter, reduce, etc). You simply plug in a function for a single item, and it takes care of doing it to the whole list.