https://github.com/schwa/swiftcalc
SwiftCalc
https://github.com/schwa/swiftcalc
Last synced: 10 days ago
JSON representation
SwiftCalc
- Host: GitHub
- URL: https://github.com/schwa/swiftcalc
- Owner: schwa
- License: bsd-3-clause
- Created: 2022-11-12T00:53:43.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-02-23T03:16:21.000Z (about 2 years ago)
- Last Synced: 2025-05-01T19:22:32.984Z (16 days ago)
- Language: C
- Size: 243 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# SwiftCalc
A Swift package for parsing and evaluating mathematical expressions.
The parser supports the basic math operators, variables and functions (defined in Swift). Under the hood it uses the wonder Owl Parser Generator .
Basic support for syntax coloring is provided in an extension of `AttributedString`.
## Usage
There are three main types in this package: `Compiler` which compiles an expression string into `CompiledProgram` and then `Executor` which evaluates the `CompiledProgram`. The `Executor` can be reused for multiple expressions.
```swift
import SwiftCalclet variables: [String: Value] = [
"pi": .number(.pi),
"sin": .function(Math.sin),
]
let program = try Compiler().compile("sin(1) * 10 * pi")
program.dump()
let executor = Executor(variables: variables)
let result = try executor.execute(program)
guard case let .number(resultValue) = result else {
fatalError()
}
```### Demo Screenshot
