ran*_*ent 2 f# functional-programming
我正在用F#编写一个小型控制台应用程序.
[<EntryPoint>]
let main argv =
high_lvl_funcs.print_opt
let opt = Console.ReadLine()
match opt with
| "0" -> printfn "%A" (high_lvl_funcs.calculate_NDL)
| "1" -> printfn ("not implemented yet")
| _ -> printfn "%A is not an option" opt
Run Code Online (Sandbox Code Playgroud)
从 module high_lvl_funcs
let print_opt =
let options = [|"NDL"; "Deco"|]
printfn "Enter the number of the option you want"
Array.iteri (fun i x -> printfn "%A: %A" i x) options
let calculate_NDL =
printfn ("enter Depth in m")
let depth = lfuncs.m_to_absolute(float (Console.ReadLine()))
printfn ("enter amount of N2 in gas (assuming o2 is the rest)")
let fn2 = float (Console.ReadLine())
let table = lfuncs.read_table
let tissue = lfuncs.create_initialise_Tissues ATM WATERVAPOUR
lfuncs.calc_NDL depth fn2 table lfuncs.loading_constantpressure tissue 0.0
lfuncs.calc_NDL returns a float
Run Code Online (Sandbox Code Playgroud)
这产生了这个
Enter the number of the option you want
0: "NDL"
1: "Deco"
enter Depth in m
Run Code Online (Sandbox Code Playgroud)
这意味着它打印出它想要的东西,然后直接跳到 high_lvl_funcs.calculate_NDL
我想要它生产
Enter the number of the option you want
0: "NDL"
1: "Deco"
Run Code Online (Sandbox Code Playgroud)
然后让我们假设输入0,然后计算 high_lvl_funcs.calculate_NDL
在经过一番思考和搜索之后,我认为这是因为F#想要在开始休息之前分配所有值.然后我认为我需要声明一个变量而不分配它.但人们似乎都认为这在函数式编程中很糟糕.从另一个问题:声明一个没有分配的变量
所以我的问题是,是否有可能重写代码,以便我得到我想要的流量,避免在不分配变量的情况下声明变量?
你可以通过创建calculate_NDL一个没有参数的函数来解决这个问题,而不是一个求值为float:
let calculate_NDL () =
Run Code Online (Sandbox Code Playgroud)
然后将其称为函数,match如下所示:
match opt with
| "0" -> printfn "%A" (high_lvl_funcs.calculate_NDL())
Run Code Online (Sandbox Code Playgroud)
但是我建议重构这段代码,以便calculate_NDL将任何必要的输入作为参数而不是从控制台读取它们,即分别从控制台读取输入并将它们传递给calculate_NDL.
let calculate_NDL depth fn2 =
let absDepth = lfuncs.m_to_absolute(depth)
let table = lfuncs.read_table
let tissue = lfuncs.create_initialise_Tissues ATM WATERVAPOUR
lfuncs.calc_NDL absDepth fn2 table lfuncs.loading_constantpressure tissue 0.0
Run Code Online (Sandbox Code Playgroud)
它通常是编写大量的代码尽可能是一个好主意纯粹的功能不依赖于I/O(如从标准输入读取).