Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#: how to print full list (Console.WriteLine() prints only first three elements)

Tags:

list

f#

Is it possible to print full list without using cycle? I tried:

Console.WriteLine([1;2;3;4;5])

and it prints only three first elements:

[1;2;3; ... ]
like image 922
Nike Avatar asked Mar 25 '10 21:03

Nike


4 Answers

If you want to use the built-in F# formatting engine (and avoid implementing the same thing yourself), you can use F# printing functions such as printfn. You can give it a format specifier to print an entire list (using F# formatting) or print just a first few elements (which happens when you call ToString):

> printfn "%A" [ 1 .. 5 ];;  // Full list using F# formatting 
[1; 2; 3; 4; 5]

> printfn "%O" [ 1 .. 5 ];;  // Using ToString (same as WriteLine)
[1; 2; 3; ... ]

If you want to use Console.WriteLine (or other .NET method) for some reason, you can also use sprintf which behaves similarly to printf, but returns the formatted string as the result:

Console.WriteLine(sprintf "%A" list)

The benefit of using printf or sprintf is that it also automatically deals with other F# types (for example if you have a list containing tuples, discriminated unions or records).

like image 56
Tomas Petricek Avatar answered Nov 18 '22 08:11

Tomas Petricek


No it's not possible to print the contents of an F# list without using a cycle / loop of sorts. To print every element you must enumerate each of them.

In F# though it doesn't need to be done with a loop though but instead can be done with a nice pipe operation

[1;2;3;4;5] |> Seq.iter (fun x -> printf "%d " x)

And as Juliet pointed out I could simplify this further with partial application

[1;2;3;4;5] |> Seq.iter (printf "%d ")
like image 37
JaredPar Avatar answered Nov 18 '22 08:11

JaredPar


In general, if you want to change as a way an printf "%A" prints your objects as a way fsi.exe shows values fo your type, you can apply StructuredFormatDisplayAttribute attribute to your type:

[<StructuredFormatDisplayAttribute("PP {PrettyPrinter}")>]
type Foo(a:string array) =
  let pp = Array.mapi (fun i (s: string) -> sprintf "{idx: %d len: %d contents: '%s'}" i s.Length s) a
  member x.PrettyPrinter = pp

> let foo = Foo [|"one";"two";"three"|];;
val foo : Foo =
  PP [|"{idx: 0 len: 3 contents: 'one'}"; "{idx: 1 len: 3 contents: 'two'}";
       "{idx: 2 len: 5 contents: 'three'}"|]

> printfn "%A" foo;;
PP [|"{idx: 0 len: 3 contents: 'one'}"; "{idx: 1 len: 3 contents: 'two'}";
     "{idx: 2 len: 5 contents: 'three'}"|]
val it : unit = ()
like image 8
ssp Avatar answered Nov 18 '22 07:11

ssp


A perhaps more functional way of doing it:

let nums = [1;2;3;4;5;6]
let concat acc x = acc + " " + (string x)
let full_list = List.fold concat "" nums
printfn "%s" full_list
like image 1
TwentyMiles Avatar answered Nov 18 '22 09:11

TwentyMiles