Shohei Yoshida
Shohei Yoshida's Blog

Follow

Shohei Yoshida's Blog

Follow

LeetCode 150. Evaluate Reverse Polish Notation in F#

Shohei Yoshida's photo
Shohei Yoshida
·Dec 17, 2022·

1 min read

URL

https://leetcode.com/problems/evaluate-reverse-polish-notation/description/

Code

https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/problems/0150/main.fsx

let evalRPN (tokens: string list) : int =
    let rec evalRPN' tokens stack =
        match tokens with
        | [] -> stack |> List.head |> int
        | h :: t ->
            match h with
            | "+" ->
                let n =
                    (List.head stack)
                    + (stack |> List.tail |> List.head)

                evalRPN' t (n :: (stack |> List.skip 2))
            | "-" ->
                let n =
                    (stack |> List.tail |> List.head)
                    - (List.head stack)

                evalRPN' t (n :: (stack |> List.skip 2))
            | "*" ->
                let n =
                    (stack |> List.tail |> List.head)
                    * (List.head stack)

                evalRPN' t (n :: (stack |> List.skip 2))
            | "/" ->
                let n =
                    (stack |> List.tail |> List.head)
                    / (List.head stack)

                evalRPN' t (n :: (stack |> List.skip 2))
            | _ -> evalRPN' t ((h |> int64) :: stack)

    evalRPN' tokens []
 
Share this