从控制台读取F# [英] Read from Console in F#
问题描述
有没有人知道是否有一个内置函数从控制台读取,类似于 printfn
函数?
到目前为止,我看到的唯一方法是使用 System.Console.Read()
,但它不像使用像 printfn
是。
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.
推荐答案
功能。但是,正如Brian在对Benjol的回答的评论中提到的,可以自己创建一个 scanf
函数。虽然只有%s
占位符被实现,但是这里有一个简单的草图描述如何定义 sscanf
>
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"
这篇关于从控制台读取F#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!