Home > other >  Can one pipe items one-after-another?
Can one pipe items one-after-another?

Time:04-04

I am coming from PowerShell and my idea is to pipe items from a list one-after-another.

PS> @(1,2,3,4) | ForEach-Object { Write-Output -InputObject $_ }

This is my naive attempt with direct translation but it pipes the whole list as an object.

> [4;5;6] |> printfn "%A";;
[4; 5; 6]
val it : unit = ()

I believe below is my closest attempt:

[4;5;6] |> List.map int x |> printfn "%i" x ;;

It throws me however the error:

[4;5;6] |> List.map int x |> printfn "%i" x ;;
  -----------^^^^^^^^^^^^^^

stdin(31,12): error FS0001: This expression was expected to have type
    'int list -> 'a'    
but here has type
    ''b list'

How can I properly pipe items from a list?

CodePudding user response:

If you want to print each element of a list on a separate line, this will do it:

[4;5;6] |> List.iter (printfn "%i")

List.iter is used to perform an action on each element of a list. In this case, the action is printfn %i. You might find that a little confusing, because the elements themselves are never bound to a name. This is called "point-free" programming style. In that case, you can use a lambda, like this:

[4;5;6] |> List.iter (fun x -> printfn "%i" x)

On the other hand, List.map is used to construct a new list by applying a function to each element of an existing list. So you could do something like this:

[4;5;6]
    |> List.map ((*) 2)   // [8;10;12]
    |> List.iter (printfn "%i")

This constructs the list [8;10;12] from [4;5;6] by multiplying each element of the original list by 2, and then prints each element of the new list on a separate line, as above.

  • Related