Binary digits: Difference between revisions
Content added Content deleted
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: | Line 1,144: | ||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
By translating C#'s approach, using imperative coding style (inflexible): |
|||
<lang FSharp>open System |
<lang FSharp>open System |
||
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2)</lang> |
for i in [5; 50; 9000] do printfn "%s" <| Convert.ToString (i, 2)</lang> |
||
Alternatively, by creating a function <code>printBin</code> which prints in binary (more flexible): |
|||
<lang FSharp>open System |
<lang FSharp>open System |
||
Line 1,159: | Line 1,159: | ||
[5; 50; 9000] |
[5; 50; 9000] |
||
|> List.iter printBin</lang> |
|> 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): |
Output (either version): |
||
<pre> |
<pre> |