我编写了一个小型控制台应用程序,可以在不使用任何可变变量的情况下更新类型记录。对于经验丰富的函数式程序员来说,这看起来很简单,但对我来说却是一项艰巨的工作。它有效,但有一件事我不满意。但在此之前,让我们从代码开始:
open System
//------------------------------------------------------------------------------------
// Type, no data validation to keep it simple
//------------------------------------------------------------------------------------
[<StructuredFormatDisplay("{FirstName} {LastName} is a {Age} year old {Sex}")>]
type Student = {
FirstName: string
LastName : string
Sex : char
Age: int
}
//------------------------------------------------------------------------------------
// I/O functions
//------------------------------------------------------------------------------------
let getConsoleChar message =
printf "\n%s" message
Console.ReadKey().KeyChar
let getConsoleString message =
printf "\n%s" message
Console.ReadLine()
let getConsoleInt = getConsoleString >> Int32.Parse //no tryparse to keep it simple, I'm sure you can type an integer
let isValidCommand command = [ 'f'; 'l'; 's'; 'a'; 'x'] |> List.contains command
let isStopCommand = (=) 'x'
let processCommand student command =
match command with
| 'f' -> { student with FirstName = (getConsoleString "First Name: ")}
| 'l' -> { student with LastName = (getConsoleString "Last Name: ")}
| 's' -> { student with Sex = (getConsoleChar "Sex: ")}
| 'a' -> { student with Age = (getConsoleInt "Age: ")}
| 'x' -> student
| _ -> failwith "You've just broken the Internet, theorically you cannot be here"
//------------------------------------------------------------------------------------
// Program
//------------------------------------------------------------------------------------
let initialStudent = {
FirstName = String.Empty
LastName = String.Empty
Sex = Char.MinValue
Age = 0
}
let commands = seq {
while true do
yield getConsoleChar "Update [f]irst name, [l]ast name, [s]ex, [a]ge or e[x]it: " }
let finalStudent =
commands
|> Seq.filter isValidCommand
|> Seq.takeWhile (not << isStopCommand)
|> Seq.map (fun cmd -> (initialStudent, cmd))
|> Seq.fold (fun student studentAndCommand -> processCommand student (snd studentAndCommand)) initialStudent
printfn "\n<<<< %A >>>>\n" finalStudent
Run Code Online (Sandbox Code Playgroud)
我的问题是
|> Seq.map (fun cmd -> (initialStudent, cmd))
|> Seq.fold (fun student studentAndCommand -> processCommand student (snd studentAndCommand)) initialStudent
Run Code Online (Sandbox Code Playgroud)
将 的序列转换char为 aStudent*char以便能够用 a 插入它看起来很奇怪Seq.fold。另外,如果使用initialStudent作为起点Seq.fold是合乎逻辑的,那么在映射转换中使用它会感觉很奇怪(我不确定如果将此代码推入产品中,是否有人会理解逻辑)。
是否有更好的方法来处理命令序列,或者此代码在功能世界中是否标准且可以接受?
您可以摆脱map并大大简化fold:
commands
|> Seq.filter isValidCommand
|> Seq.takeWhile (not << isStopCommand)
|> Seq.fold processCommand initialStudent
Run Code Online (Sandbox Code Playgroud)
我不知道为什么你认为你必须首先将 a 映射seq<char>到 a 中。seq<Student * char>由于您立即使用从元组中snd提取char,撤消映射,因此元组的第一个元素将被完全忽略。更干净,可以从一开始就避免创建元组