Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from Console in F#

Tags:

console

f#

Does anyone know if there is a builtin function for reading from the console likewise to the printfn function? The only method I've seen so far is using System.Console.Read() but it doesn't feel as functional as using a construct like printfn is.

like image 288
Aurril Avatar asked Mar 10 '10 09:03

Aurril


People also ask

What is console read () in C#?

Read() Method is used to read the next character from the standard input stream.

What is console ReadLine in VB net?

The ReadLine method reads a line from the standard input stream. (For the definition of a line, see the paragraph after the following list.) This means that: If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key.


2 Answers

It is indeed a shame that there is no such built-in function. However, as Brian mentioned in a comment on Benjol's answer, it is possible to build a scanf function yourself. Here's a quick sketch of how one might define a sscanf variant, although only %s placeholders are implemented:

open System
open System.Text
open System.Text.RegularExpressions
open Microsoft.FSharp.Reflection

let sscanf (pf:PrintfFormat<_,_,_,_,'t>) s : 't =
  let formatStr = pf.Value
  let constants = formatStr.Split([|"%s"|], StringSplitOptions.None)
  let regex = Regex("^" + String.Join("(.*?)", constants |> Array.map Regex.Escape) + "$")
  let matches = 
    regex.Match(s).Groups 
    |> Seq.cast<Group> 
    |> Seq.skip 1
    |> Seq.map (fun g -> g.Value |> box)
  FSharpValue.MakeTuple(matches |> Seq.toArray, typeof<'t>) :?> 't


let (a,b) = sscanf "(%s, %s)" "(A, B)"
let (x,y,z) = sscanf "%s-%s-%s" "test-this-string"
like image 172
kvb Avatar answered Oct 22 '22 14:10

kvb


As far as I know, no.

It would be handy for code golf :)

like image 34
Benjol Avatar answered Oct 22 '22 12:10

Benjol