在 F# 中从控制台读取 [英] Read from Console in F#

查看:24
本文介绍了在 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 函数.这是一个如何定义 sscanf 变体的快速草图,尽管只实现了 %s 占位符:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆