Copyright(c) Tim B. Herbstrith 2017
LicenseMIT
MaintainerPlease contact me via GitHub!
Stabilityexperimental
PortabilityPOSIX
Safe HaskellSafe

Main

Contents

Description

Language : Haskell2010

A simple RPN calculator written in Haskell

Synopsis

Functions for user interactions

type Stack = [Double] #

All numerals for computations are stored in a stack of arbitrary size

main :: IO () #

Starts the main recursion with empty stack

calc :: Stack -> IO () #

Gets command and updates stack according to user input.

The command "show" will print the stack. All other inputs will be passed to parsing. At the end calc is called with the updated stack.

showHead :: Stack -> String #

Returns string representation of the first item on the stack. If the stack is empty, the string Nothing is returned.

updateStack #

Arguments

:: Stack

The old stack

-> Maybe Stack

Hopefully the new one

-> IO Stack 

Safely updates the stack by checking first if Maybe Stack is Nothing the user will be informed and the old stack is returned. Otherwise the stack is extracted and returned.

Functions for parsing

parsing :: Stack -> [String] -> Maybe Stack #

Takes a list of commands and applys them sequencially to the stack.

If a computation fails, Nothing is returned.

Examples:

>>> parsing [] $ words "3 2 ^ 4 2 ^ + sqrt"
Just [5.0]
>>> parsing [2.0] ["/"] -- Too few arguments on stack!
Nothing

pars :: Stack -> String -> Maybe Stack #

Parses command and applys the corresponding function to the first elements of the stack.

If the command is not recognised or there are too few numbers on the stack, Nothing is returned.

Examples:

>>> let stack = [-6.0, 2.0] :: Stack
>>> pars stack "*"
Just [-12.0]
>>> pars stack "abs"
Just [6.0,2.0]
>>> pars stack ".."
Just [-6.0,-5.0,-4.0,-3.0,-2.0,-1.0,0.0,1.0,2.0]
>>> pars stack "katze" -- I can't imagine such a command exists
Nothing
>>> pars stack "4.3"
Just [4.3,-6.0,2.0]
>>> pars stack "4,3" -- Damn you German decimal separator
Nothing

Operators and Helper Functions

contNum :: String -> Bool #

Checks whether a string contains a numeral

fac :: (RealFrac a, Eq a, Ord a) => a -> a #

A Double implementation for the factorial

Note:

Doubles will be truncated.

Example:

>>> fac 4.2
24.0

nCr :: Double -> Double -> Double #

A Double implementation for "n choose r"

Note:

Doubles will be truncated.

nCr' :: Integral a => a -> a -> a #

The backbone of nCr

getMaybe :: Integral i => [a] -> i -> Maybe a #

Safely retrieves (l - i - 1)-th value of a list

Note:

The function retrieves this value because it is the i-th value that was pushed to the stack

Example

>>> let xs = [1..5]
>>> getMaybe xs 0
Just 5
>>> getMaybe xs 1
Just 4
>>> getMaybe xs 5 -- Index to large
Nothing
>>> getMaybe xs (-2)
Nothing