简体   繁体   English

FSharp F#中的字符串编辑问题

[英]String editing issues in FSharp F#

I'm quite new to the F# language and functional first approach, as I have only been working with Object Oriented languages. 我对F#语言和功能优先的方法还很陌生,因为我只使用面向对象的语言。

Im trying to create a simple Word Guesser Console Application. 我正在尝试创建一个简单的Word Guesser控制台应用程序。 The feature i'm working on is to be able to guess for multiple characters at once 我正在使用的功能是能够一次猜出多个字符

I have a hard time piecing together a nice way to do this, as i want to take a functional approach, and always end up having issues with immutable arrays and such. 我很难拼凑一个很好的方法来完成此操作,因为我想采用一种功能性方法,并且最终总是遇到不可变数组等问题。

Here is what I have come up with: 这是我想出的:

Im trying to replace/reveal the chars on the indexes of the given word, which corresponds the guess and return the resulting string 我试图替换/显示给定单词的索引上的字符,这对应于猜测并返回结果字符串

Any Leads? 有线索吗?

Kindly Regards Kalrin 亲切的问候

A functional way easy to get would be to use a match but to regenerate a new string. 一种容易获得的功能性方法是使用匹配项,但重新生成新的字符串。

You may also want to use a Some/None (which will give you an option string as a result of your function if you look at its signature, this is a functional way to write it but if you need an empty chain, you can also return one). 您可能还想使用Some / None(如果您查看函数的签名,它会为您提供一个作为函数结果的选项字符串),这是一种实用的编写方法,但是如果您需要一个空链,也可以返回一个)。 Please refer to the bible for F# fsharpforfunandprofit.com 请参阅F#的圣经fsharpforfunandprofit.com

A few comments: 一些评论:

  • OOP in .Net (let's say C#) : You would use Substring method instead of your for loop .NET中的OOP(假设为C#):您将使用Substring方法而不是for循环
  • Be careful, Substirng can return an exception (if you put your mouse on it, it tells you so in the messagebox) and to avoid any issue at run time (as we usually do not work with exceptions in F# - cf Railway programming on fsharpforfunandprofit), you need a second match to check the length. 请注意,Substirng可以返回异常(如果您将鼠标放在其上,它会在消息框中告诉您),并避免在运行时出现任何问题(因为我们通常不使用F#中的异常-cf fsharpforfunandprofit的铁路编程),则需要进行第二次匹配才能检查长度。

https://fsharpforfunandprofit.com/posts/the-option-type/ https://fsharpforfunandprofit.com/posts/the-option-type/

let stringContains (word:string) (hidden:string) (guess:string) =
    match word.IndexOf(guess) with
    | -1 -> None
    | ind -> match (hidden.Length < ind) with
                     | true -> Some (guess)
                     | false -> Some (hidden.Substring(0, ind) + guess)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM