Seinfeld
Seinfeld

Reputation: 433

F# print all element from the list one by one using recursion

Imagine that I have function printList that takes list as an argument and prints all the elements in the list one by one in a new row followed by the position in the list also while having space between them.

E.G

1: 4
2: 9
3: 12

How can I implement this in F# using recursion without any built-in features ?

I assume it might look something like this, but I've problems with int, unit types.

let rec printList l = function
    match l with
    | [] -> 0
    | head::tail -> // something

Upvotes: 1

Views: 1320

Answers (1)

user9895453
user9895453

Reputation:

There are two advices I can give you so you can implement the printList function:

  • you will have to make printList a non-recursive function and define a local recursive helper function in order to keep track of the index of the value.
  • all branches of your match expression must return the same type and here what you want is the unit type.

In case you are still stuck, I provide the solution below.


Solution

let printList list =
  let rec helper index list =
    match list with
    | [] -> ()
    | head :: tail ->
      printfn "%d: %A" index head
      helper (index + 1) tail

  helper 1 list

Upvotes: 3

Related Questions