functional programming - How to execute specific functions with input pattern in F# language -
i'm kinda new f# , trying out simple calculator app. take input user, , want specific functions executed per input. right now, whenever take input user, program executes top bottom. want execute specific functions matching input. if input 6 body of scientificfun() should executed. right executes functions. please help, i'm kinda stuck on one! code is
open system let mutable ok = true while ok console.writeline("choose operation:\n1.addition\n2.substraction\n3.multiplication\n4.division\n5.modulo\n6.scientific") let input= console.readline() let add = console.writeline("ok, how many numbers?") let mutable count = int32(console.readline()) let numberarray = array.create count 0.0 in 0 .. numberarray.length - 1 let no = float(console.readline()) array.set numberarray no array.sum numberarray let sub x y = x - y let mul x y = x * y let div x y = x / y let mod x y = x % y let scientificfun() = printfn("1. exponential") match input | "1" -> printfn("the result is: %f") (add) | "6" -> (scientificfun()) | _-> printfn("choose between 1 , 6") console.writeline("would use calculator again? y/n") let ans = console.readline() if ans = "n" ok <- false else console.clear()
you should define add function: let add() = or let add inputnumbers =
otherwise simplified version below executes functions corresponding input number:
open system [<entrypoint>] let main argv = // define functions let hellofun() = printfn "%a" "hello" let worldfun() = printfn "%a" "world" let mutable cont = true let run() = // set while loop while cont printfn "%a" "\nchoose operation:\n 1 hellofunc\n 2 worldfunc\n 3 exit" let input = console.readline() // input match input // pattern match on input call correct function | "1" -> hellofun() | "2" -> worldfun() | "3" -> cont <- false;() | _ -> failwith "unknown input" run() // kick-off loop 0 the [<entrypoint>] let main argv = necessary if compile it. otherwise execute run().
Comments
Post a Comment