Read from Console in F#

只愿长相守 提交于 2019-12-20 11:59:08

问题


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.


回答1:


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"



回答2:


As far as I know, no.

It would be handy for code golf :)




回答3:


Combination of TryParse() and split/regex is what you can use "out of box".

P.S. i've seen http://www.codeproject.com/KB/recipes/csscanf.aspx and it works ;)



来源:https://stackoverflow.com/questions/2415705/read-from-console-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!