openlang

Formatting list elements as text with functional programming

I'm a functional programming beginner, trying to create a function which accepts values in a list (whose length isn't fixed) and produces a string containing a formatted representation of every value.

As an example (using pseudocode):

 render_entries([2, 3, 4])
 // -> "entry: 2, entry: 3, entry: 4"

(My particular language is Gleam (https://gleam.run/), although I'd expect the idea to apply to other functional languages with only syntactic differences)

How would I accomplish that?

The conversation continues 2

Follow the reasoning
  1. Permalink

    I've worked it out. For my particular Gleam example:

     list.fold(entries, "", fn(buffer, entry) -> String {
       buffer + "entry: " + int.to_string(entry) + " "
     })
  2. Permalink

    a function receiving a list and producing a (???) for every value

    Functional languages normally call this operation "map". There is a list function called map in Gleam (https://hexdocs.pm/gleam_stdlib/gleam/list.html#map), which seems to match what you need. For example, with an expression such as

     list.map([2, 3, 4], fn(entry) { "entry: " <> int.to_string(entry) })

    the result would be a list containing the transformed entries. Afterwards, list.intersperse (https://hexdocs.pm/gleam_stdlib/gleam/list.html#intersperse) lets you join that list with an extra entry placed between successive elements (a helper that isn't nearly as universal in functional languages).

    Gleam appears to offer pipelines similar to Elixir's (https://tour.gleam.run/functions/pipelines/), so I'd perhaps express it as

     [2, 3, 4]
     |> list.map(fn(entry) { "entry: " <> int.to_string(entry) })
     |> list.intersperse(", ")

    Two more operations that I regard as fundamental across functional programming include reduce or fold, taking a list down to one result, and filter, accepting a list plus a predicate and producing a list containing the entries passing that predicate. Some can be expressed through others (in particular, fold can implement map as well as filter, albeit perhaps inefficiently), but in my experience selecting the appropriate operation is easier to follow and frequently quicker.

Other sides of the same question

  1. Lean4 reports that 'begin' is unknown

    In the VSCode editor, I entered this Lean4 code: and got "unknown identifier 'begin'". Adding end three lines below gives "in…

    Replies 2Latest activity lean-4
  2. A JavaScript class to take?

    The last year I consulted JavaScript documentation was 1996. I'd like an educational course covering the “essential JavaScrip…

    Replies 2Latest activity elmjavascript
  3. Where can I find fmt and the main package?

    Lots of go examples begin with : The GOPATH I use: Where are main and the fmt module stored?

    Replies 2Latest activity go