Jump to content

Binary digits: Difference between revisions

→‎{{header|F Sharp|F#}}: added method to use with "%a" which is a specific technique for F# and not available directly in C#, for instance
No edit summary
(→‎{{header|F Sharp|F#}}: added method to use with "%a" which is a specific technique for F# and not available directly in C#, for instance)
Line 1,144:
 
=={{header|F Sharp|F#}}==
TranslationBy oftranslating C#'s approach, using imperative coding style (inflexible):
<lang FSharp>open System
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2)</lang>
 
Alternative wayAlternatively, by creating a function <code>printBin</code> which prints in binary (more flexible):
<lang FSharp>open System
 
Line 1,159:
[5; 50; 9000]
|> List.iter printBin</lang>
 
Or more idiomatic so that you can use it with any printf-style function and the <code>%a</code> format specifier (most flexible):
 
<lang FSharp>open System
open System.IO
 
// define a callback function for %a
let bin (tw: TextWriter) value =
tw.Write("{0}", Convert.ToString(int64 value, 2))
 
// use it with printfn with %a
[5; 50; 9000]
|> List.iter (printfn "binary: %a" bin)</lang>
Output (either version):
<pre>
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.