Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over each item once within a list in f# functionally?

Hi i was wondering is there was a way to iterate over each item once within a list, in java i would use a for each loop to access each item within an arraylist, however i want to take a functional approach with f#. The best method i can think of would be to use the first item in the head of the list then delete it so the next item will be the head (then carry on until there is no more values left with the list). the only problem with that is i dont know how to implement it as i am still very new to this language. any help will be appreciated.

for convenience sake lets assume i have a list:

let mylist = ["hello";"bird";"dog";"cat";"snake"]
like image 250
Ashraf Rahman Avatar asked May 10 '17 18:05

Ashraf Rahman


1 Answers

Idiomatic version

If you just want to do this in regular F# code, rather than for educational purposes, then the easiest option is to use for. This is not particularly functional, but since the task is imperative in its nature, this is the way to go:

for item in mylist do
  printfn "%s" item

Higher-order function

A bit more functionally-looking solution is to use higher-order function List.iter. This is useful as part of longer pipelines, but it illustrates some functional features, namely using functions as arguments:

mylist |> List.iter (fun item ->
  printfn "%s" item)

Recursive version

Finally, you can also do this using recursion and pattern matching on lists. This is essentially what List.iter does behind the scenes - rather than "deleting" the head, this decomposes the list into head and tail and then processes the tail recursively after printing the item in the head:

let rec iter items = 
  match items with
  | [] -> ()
  | head::tail -> 
     printfn "%s" head
     iter tail

iter mylist
like image 190
Tomas Petricek Avatar answered Nov 15 '22 12:11

Tomas Petricek