【问题标题】:F# - Save the previous printed textF# - 保存之前的打印文本
【发布时间】:2017-03-15 14:54:18
【问题描述】:

所以我有一个包含字符的文本文件,我让用户通过在控制台中打印来读取(通过将文件内容读入字符列表并将其转换为字符串),之后我试图让用户更改char 列表中的一个字母。但是,这样做我将不得不执行一个循环并访问包含字符列表的变量并循环遍历它,然后将其保存在同一个变量(或新变量)中以向用户显示以供批准,如果不是,用户应该能够通过运行相同的循环再次更改字符。

虽然我的问题是我无法找到一种方法来更改包含字符列表的变量而不使变量可变。对这个问题有什么建议吗?

            while true do            
                Console.Write("\n\nDo you want to change some tokens? press 1 or 2 to end: ")
                let rep = Console.ReadLine() |> int
                if rep = 1 then
                    Console.Write("\n\n Enter the token you will change in the text : ")
                    let user = Console.ReadLine() |> char
                    let k1 = user
                    Console.Write("\n Enter your token you will replace TO : ")
                    let user2 = Console.ReadLine() |> char
                    let k2 = user2
                    let t = finalList
                    let finalList2 = swap t k1 k2
                    let f2 = finalList2 |> charListToString

                    printfn "%s" f2

从上面的代码实现中可以看出,我只能更改一次列表,如果循环再次运行,它将丢失之前更改的第一个值。

【问题讨论】:

    标签: f# functional-programming


    【解决方案1】:

    没有声称这是最好的解决方案,但根据您的问题,我认为这是您想要实现的目标;一个简单的在字符串中逐个字符地查找和替换?

    这是一个使用递归函数和内部模式匹配用户按下的键的解决方案。它应该可以帮助您入门,将其放入 .fsx 文件并在 fsx 文件的命令行上调用 fsc,然后您可以调用生成的 exe 并查看它的作用。

    open System
    
    let rec change ( data : string ) =
      printfn "\n1 to make changes or 2 to quit"
      let keyPressed = Console.ReadKey() 
      match keyPressed.KeyChar with
      | '1' -> 
        printfn "\nEnter the character in the string you want to change:"
        let changeChar = Console.ReadKey().KeyChar
        printfn "\nEnter the character to change to:"
        let changeTo = Console.ReadKey().KeyChar
        let newData = data.ToCharArray() |> Array.map ( fun c -> if c = changeChar then changeTo else c ) |> String
        printfn "\n%s\n" newData
        change newData
      | '2' -> data
      | _ -> change data
    
    [<EntryPoint>]
    let Main args =
      printfn "\n%s\n" <| change "abc"
    
      0
    

    【讨论】:

    • 感谢您的回复,但我已经想到了这一点,我的问题是用户在列表中更改了一次字符后,第二次用户应该能够继续更改更改的列表就像解密一样。
    • 我正在尝试在使用令牌和字符列表的地方进行解密。用户应该能够通过输入如此多的尝试来更改文件中的所有标记和字符,直到文本文件清晰可读为止。我已经弄清楚了所有的功能和输入,但问题是当用户在第一次尝试中更改字符然后在第二次尝试中它将恢复第一个更改的字符并更改一个新字符。但我希望用户可以继续并更改剩余字符并在控制台中更新新结果。
    • 据我所知,这正是 Mr. Mr. 的解决方案。你试过运行它吗?
    猜你喜欢
    • 2019-07-07
    • 2013-03-21
    • 2020-01-28
    • 2012-05-02
    • 1970-01-01
    • 2021-07-10
    • 2016-09-26
    • 1970-01-01
    • 2012-09-13
    相关资源
    最近更新 更多