this is my first F# program, very simple concept but took me a few minutes to get it. I'm new to functional programming so I'd appreciate if you could have a look at and comment the code.

Suggest changes or any code smells?

module FSharpFun.PrintSentenceInLines

open System

let printWord w = printfn "%s" w
let printEveryWord = Array.map printWord
let splitIntoWords (s:String) = s.Split ()

// Read a line and print each word in a new line
let main _ =
    Console.ReadLine () |> splitIntoWords |> printEveryWord |> ignore
  • \$\begingroup\$ Array.iter instead of Array.map is a more appropriate here. Then we can eventually get rid of the last |> ignore. Finally and less important, we could inline printEveryWord because Array.iter printWord reads well enough. \$\endgroup\$ – Romain Deneau May 14 at 18:09
  • \$\begingroup\$ Just made the changes, it looks much better, I will read up a bit to understand why I didn't need the last |> ignore. Now that I've made the change this program looks even more basic, but that's ok. Baby steps :) Thanks a lot \$\endgroup\$ – Santanor May 15 at 9:33
  • 1
    \$\begingroup\$ When you use Array.map the result is another array, of Units, one per each word you printed. That array needs to be ignore-ed since it's a value and the F# compiler likes its values to be "attached" to something. Opting for Array.iter gives you a single Unit as output, and Unit is a sort of "no data value", so the compiler ignores it on its own. (This is, of course, very figurative, but it's "correct enough" to explain why iter is better, more correct even). And, as Romain said, just go with ... |> Array.iter (fun w -> printfn $"%s{w}") \$\endgroup\$ – The one that loves FP Jun 9 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.