Advertisement
Guest User

Untitled

a guest
Feb 16th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.99 KB | None | 0 0
  1. //Project $safeprojectname$
  2. //Created by Björn Dagerman 2015/05 (dagerman@kth.se)
  3. //
  4. //TestModule: A module with a simple function for demo purposes
  5. namespace Demo
  6. open System.Text.RegularExpressions
  7.  
  8. module TestModule =
  9.     let printList list = if list <> [] then printfn "%A" list
  10.  
  11.     type GenTree<'data> =
  12.      |Leaf of 'data
  13.       |SubTree of  GenTree<'data> * 'data * GenTree<'data>
  14.  
  15.    type Calc =
  16.        |Operator of (float->float->float)
  17.        |Operand of float
  18.  
  19.    let IsOperator (str:string) =
  20.        match str with
  21.        | "+" | "-" | "x" | "/" -> true
  22.        |_ -> false
  23.  
  24.    let parseToFloat (str:string) =
  25.        System.Single.Parse str
  26.  
  27.    let parseAsString (str:string list) =
  28.        let StringOfExpressions = System.String.Concat(List.toSeq str)
  29.        let delimiters = "(\+|x|\/|\-)"
  30.        Regex.Split (StringOfExpressions, delimiters)
  31.  
  32.  
  33.    let ParseToOperator (str:string) =
  34.        match str with
  35.        |"+" -> (+)
  36.        |"-" -> (-)
  37.        |"x" -> (*)
  38.        |"/" -> (/)
  39.        |_ -> failwith "Not valid operator"
  40.  
  41.    let BuildTree (t1, t2, t3) =
  42.        SubTree(t1,t2,t3)
  43.  
  44.    let CheckFirstExpression (list:string list) =
  45.        match list with
  46.        |x::x2::x3::xs when (not (IsOperator x)) && (IsOperator x2) && (not (IsOperator x3)) -> BuildTree(Leaf (Operand (float x)), (Operator (ParseToOperator x2)), Leaf (Operand (float x3)))
  47.        |_ -> failwith "This expression is incomplete"
  48.  
  49.    let rec eval tree =
  50.        match tree with
  51.        |Leaf (Operand x) -> x
  52.        |SubTree(tl,oper,tr) -> match oper with
  53.                                            |Operator (+) -> (eval tl) + (eval tr)
  54.                                            |Operator (-) -> (eval tl) - (eval tr)
  55.                                            |Operator (*) -> (eval tl) * (eval tr)
  56.                                            |Operator (/) -> (eval tl) / (eval tr)
  57.                                            |_-> failwith "wrong operator"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement