Iterate a list and make uppercase

Hello;
A . We have a list and we want to iterate over it one by one and then print each elements in uppercase.

for i in [“Julia”; “jaCK”; “tRacy”; “JohN”] do
printfn “%s” i.ToUpper

“This function takes too many arguments, or is used in a context where a function is not expected”
What??? I mean really :dizzy_face:

B. We want to go through elements of a list and this time return a list but with its elements uppcased.
How should we do that? (When the list is immutable)

thanks

Hello, and welcome @sahar.sedigh

A. ToUpper in this case is a method instead of just a field/property. That means it’s kind of like a function and in this case it takes in “unit” (written as ()) as an input. You can correct it by changing it to

for i in [“Julia”; “jaCK”; “tRacy”; “JohN”] do 
  printfn “%s” (i.ToUpper())

Note the parentheses are needed around i.ToUpper() or else the compiler will interpret it as if you were passing the () into printfn, like

printfn "%s" i.ToUpper()
// same to the compiler as 
printfn ("%s") (i.ToUpper) ()

B. The most idiomatic F# way would be via the List.map function. It’s built exactly for transforming each element of a list while leaving everything immutable. That would look like

let names = [“Julia”; “jaCK”; “tRacy”; “JohN”]
let ucaseNames = names |> List.map (_.ToUpper())

It’s really valuable to browse through the functions in the List module and get a good handle on them. But if you don’t have much familiarity with the List module, you can do a lot of things with for loops and “list comprehensions”. In this case you could write it as

let names = [“Julia”; “jaCK”; “tRacy”; “JohN”]
let ucaseNames = 
  [ for name in names do
      yield name.ToUpper() ]
// or when every iteration yields just a single element, you can simplify to
let ucaseNames = [ for name in names -> name.ToUpper() ]
1 Like