### MAP and SUM Functions for Calculations in Dentaku Source: https://context7.com/rubysolo/dentaku/llms.txt Illustrates the use of MAP to transform elements of a collection and SUM to aggregate the results. This example shows how to combine these functions to perform calculations, such as calculating the total cost based on price and quantity for each item in a list. ```ruby calculator.evaluate('SUM(MAP(items, i, i.price * i.qty))', items: [ { 'price' => 10, 'qty' => 2 }, { 'price' => 20, 'qty' => 3 }, { 'price' => 5, 'qty' => 4 } ]) #=> 100 ``` -------------------------------- ### Use Built-in Logical and Conditional Functions Source: https://context7.com/rubysolo/dentaku/llms.txt Examples of using Excel-like logical functions such as IF, AND, OR, and SWITCH to handle conditional logic within expressions. ```ruby calculator = Dentaku::Calculator.new # IF function: IF(condition, true_value, false_value) calculator.evaluate('IF(pears < 10, 10, 20)', pears: 5) #=> 10 # Nested IF calculator.evaluate('IF(score >= 90, "A", IF(score >= 80, "B", "C"))', score: 85) #=> "B" # SWITCH function - matches value against cases calculator.evaluate('SWITCH(grade, "A", 4.0, "B", 3.0, "C", 2.0, 0.0)', grade: "B") #=> 3.0 ``` -------------------------------- ### Use Built-in Functions Source: https://github.com/rubysolo/dentaku/blob/main/README.md Examples of using built-in functions like SUM, IF, and ROUND within expressions. ```ruby calculator = Dentaku::Calculator.new calculator.evaluate('SUM(1, 1, 2, 3, 5, 8)') calculator.evaluate('if (pears < 10, 10, 20)', pears: 5) calculator.evaluate('round(8.2759, 2)') ``` -------------------------------- ### Dentaku: Combined String Operations and Logic Source: https://context7.com/rubysolo/dentaku/llms.txt Shows examples of combining string functions with conditional logic (IF) and other string operations for more complex text manipulations and data validation. ```ruby calculator = Dentaku::Calculator.new calculator.evaluate('IF(CONTAINS("@", email), "Valid", "Invalid")', email: "user@example.com") #=> "Valid" calculator.evaluate('CONCAT(LEFT(name, 1), ". ", last_name)', name: "John", last_name: "Doe") #=> "J. Doe" ``` -------------------------------- ### Dentaku: String Functions (LEFT, RIGHT, MID, LEN, CONCAT) Source: https://context7.com/rubysolo/dentaku/llms.txt Covers essential string manipulation functions in Dentaku, including extracting substrings (LEFT, RIGHT, MID), getting string length (LEN), and concatenating strings (CONCAT). These functions follow Excel-like conventions. ```ruby calculator = Dentaku::Calculator.new # LEFT - extract characters from start calculator.evaluate('LEFT("Hello World", 5)') #=> "Hello" # RIGHT - extract characters from end calculator.evaluate('RIGHT("Hello World", 5)') #=> "World" # MID - extract substring (1-indexed offset) calculator.evaluate('MID("Hello World", 7, 5)') #=> "World" # LEN - string length calculator.evaluate('LEN("Hello")') #=> 5 # CONCAT - concatenate strings (variadic) calculator.evaluate('CONCAT("Hello", " ", "World")') #=> "Hello World" calculator.evaluate('CONCAT(first_name, " ", last_name)', first_name: "John", last_name: "Doe") #=> "John Doe" ``` -------------------------------- ### Get Expression Dependencies - Ruby Source: https://github.com/rubysolo/dentaku/blob/main/README.md Retrieves a list of variables required for a given mathematical expression. It considers variables already stored in the calculator instance. Returns an empty array if all dependencies are met. ```ruby calc.dependencies("monthly_income * 12") #=> [] # (since monthly_income is in memory) calc.dependencies("annual_income / 5") #=> [:annual_income] ``` -------------------------------- ### Evaluate Basic Mathematical Expressions Source: https://github.com/rubysolo/dentaku/blob/main/README.md Demonstrates how to initialize a Dentaku calculator and evaluate simple arithmetic strings. ```ruby calculator = Dentaku::Calculator.new calculator.evaluate('10 * 2') ``` -------------------------------- ### Enable AST Caching for Performance Source: https://github.com/rubysolo/dentaku/blob/main/README.md Shows how to enable AST caching to significantly speed up repeated evaluations of the same formulas. ```ruby Dentaku.enable_ast_cache! ``` -------------------------------- ### Dentaku: Comparison Operators Source: https://context7.com/rubysolo/dentaku/llms.txt Demonstrates the use of various comparison operators within Dentaku's expression language. These operators allow for evaluating relationships between numerical values and are essential for conditional logic. ```ruby calculator.evaluate('5 > 3') #=> true calculator.evaluate('5 < 3') #=> false calculator.evaluate('5 >= 5') #=> true calculator.evaluate('5 <= 4') #=> false calculator.evaluate('5 = 5') #=> true calculator.evaluate('5 <> 3') #=> true (not equal) calculator.evaluate('5 != 3') #=> true (not equal) ``` -------------------------------- ### Dentaku: Exponentiation ( ^, POW) Source: https://context7.com/rubysolo/dentaku/llms.txt Shows how to perform exponentiation using both the '^' operator and the POW function in Dentaku. These are equivalent and used for calculating powers. ```ruby calculator.evaluate('2 ^ 10') #=> 1024 calculator.evaluate('POW(2, 10)') #=> 1024 ``` -------------------------------- ### Optimize Performance with AST Caching Source: https://context7.com/rubysolo/dentaku/llms.txt Covers enabling AST caching to speed up repeated evaluations of the same formulas. Includes methods for global cache activation, pre-loading common formulas, and injecting existing caches into new instances. ```ruby Dentaku.enable_ast_cache! calculator = Dentaku::Calculator.new calculator.evaluate('complex_formula * rate + base', complex_formula: 100, rate: 0.15, base: 10) existing_cache = { 'x + y' => calculator.ast('x + y') } new_calculator = Dentaku::Calculator.new new_calculator.load_cache(existing_cache) ``` -------------------------------- ### PLUCK and REDUCE Functions Source: https://context7.com/rubysolo/dentaku/llms.txt Demonstrates the usage of PLUCK for extracting values from collections and REDUCE for aggregating collection data. ```APIDOC ## PLUCK Function ### Description Extracts a specific key's value from each item in a collection. Supports a default value for missing keys. ### Syntax `PLUCK(collection, key, default_value)` ### Parameters - **collection** (array) - The collection to process. - **key** (string) - The key whose values to extract. - **default_value** (any, optional) - The value to return if the key is not found in an item. ### Examples ```ruby users = [ { 'name' => 'Alice', 'age' => 30 }, { 'name' => 'Bob', 'age' => 25 }, { 'name' => 'Charlie', 'age' => 35 } ] calculator.evaluate('PLUCK(users, name)', users: users) #=> ["Alice", "Bob", "Charlie"] calculator.evaluate('PLUCK(users, age)', users: users) #=> [30, 25, 35] users_with_missing = [ { 'name' => 'Alice', 'role' => 'admin' }, { 'name' => 'Bob' } ] calculator.evaluate('PLUCK(users, role, "user")', users: users_with_missing) #=> ["admin", "user"] ``` ## REDUCE Function ### Description Reduces a collection to a single value by applying an expression iteratively. ### Syntax `REDUCE(collection, accumulator, item, expression, initial_value)` ### Parameters - **collection** (array) - The collection to reduce. - **accumulator** (string) - The name of the variable that holds the accumulated value. - **item** (string) - The name of the variable representing the current item in the collection. - **expression** (string) - The expression to evaluate for each item, updating the accumulator. - **initial_value** (any) - The starting value for the accumulator. ### Examples ```ruby calculator.evaluate('REDUCE(numbers, sum, n, sum + n, 0)', numbers: [1, 2, 3, 4, 5]) #=> 15 calculator.evaluate('REDUCE(numbers, product, n, product * n, 1)', numbers: [1, 2, 3, 4]) #=> 24 ``` ## Combined Collection Functions ### Description Demonstrates combining collection functions like SUM and MAP. ### Example ```ruby calculator.evaluate('SUM(MAP(items, i, i.price * i.qty))', items: [ { 'price' => 10, 'qty' => 2 }, { 'price' => 20, 'qty' => 3 }, { 'price' => 5, 'qty' => 4 } ]) #=> 100 ``` ``` -------------------------------- ### Dentaku: Collection Aggregation (ALL, ANY) Source: https://context7.com/rubysolo/dentaku/llms.txt Illustrates the ALL and ANY functions for checking conditions across all or any elements within a collection, respectively. They take a collection, an item identifier, and a condition. ```ruby calculator = Dentaku::Calculator.new # ALL - check if all elements match condition # Syntax: ALL(collection, item_identifier, condition) calculator.evaluate('ALL(scores, s, s >= 60)', scores: [70, 80, 90]) #=> true calculator.evaluate('ALL(scores, s, s >= 60)', scores: [70, 55, 90]) #=> false # ANY - check if any element matches condition # Syntax: ANY(collection, item_identifier, condition) calculator.evaluate('ANY(scores, s, s >= 90)', scores: [70, 80, 95]) #=> true calculator.evaluate('ANY(scores, s, s >= 90)', scores: [70, 80, 85]) #=> false ``` -------------------------------- ### Dentaku: Mathematical Functions (INTERCEPT, SQRT, SIN, LOG, PI) Source: https://context7.com/rubysolo/dentaku/llms.txt Demonstrates advanced mathematical functions available in Dentaku, including statistical (INTERCEPT) and trigonometric/logarithmic functions (SQRT, SIN, COS, TAN, LOG, PI). These are often wrappers around Ruby's Math module. ```ruby calculator = Dentaku::Calculator.new # INTERCEPT - linear regression intercept calculator.evaluate('INTERCEPT(known_ys, known_xs)', known_ys: [2, 3, 9, 1, 8], known_xs: [6, 5, 11, 7, 5]) #=> 0.04838709677419217 # Ruby Math functions (SIN, COS, TAN, SQRT, LOG, etc.) calculator.evaluate('SQRT(16)') #=> 4.0 calculator.evaluate('SIN(0)') #=> 0.0 calculator.evaluate('LOG(100, 10)') #=> 2.0 calculator.evaluate('PI()') #=> 3.141592653589793 ``` -------------------------------- ### Evaluate Formulas with Global Shorthand Functions Source: https://context7.com/rubysolo/dentaku/llms.txt Utilize Dentaku() for permissive evaluation that returns nil on error, and Dentaku!() for strict evaluation that raises specific exceptions. These functions allow for quick calculations without manual calculator instantiation. ```ruby require 'dentaku' # Permissive Dentaku('10 * 2') Dentaku('invalid expression +') # returns nil # Strict begin Dentaku!('missing_var + 1') rescue Dentaku::UnboundVariableError => e puts "Error: #{e.message}" end ``` -------------------------------- ### Register Custom Functions in Dentaku Source: https://context7.com/rubysolo/dentaku/llms.txt Demonstrates how to add custom functions to the calculator, including support for variadic arguments, specific return types, and side-effect callbacks. Functions can be registered on individual instances or globally. ```ruby calculator = Dentaku::Calculator.new calculator.add_function(:double, :numeric, ->(x) { x * 2 }) calculator.add_function(:product, :numeric, ->(*args) { args.reduce(1, :*) }) calculator.add_function(:log_value, :numeric, ->(x) { x }, ->(result) { puts "Logged: #{result}" }) Dentaku::Calculator.add_function(:global_tax, :numeric, ->(amount) { amount * 0.1 }) ``` -------------------------------- ### Solving Dependent Formulas with Dentaku's solve! and solve Source: https://context7.com/rubysolo/dentaku/llms.txt Details how Dentaku's `solve!` and `solve` methods automatically resolve dependencies between formulas using topological sorting. It covers basic dependency resolution, complex interdependent formulas, handling missing dependencies, and detecting circular dependencies. ```ruby calculator = Dentaku::Calculator.new calculator.store(monthly_income: 5000) formulas = { annual_income: "monthly_income * 12", income_taxes: "annual_income * 0.25", net_income: "annual_income - income_taxes" } results = calculator.solve!(formulas) #=> {annual_income: 60000, income_taxes: 15000.0, net_income: 45000.0} calculator.store( base_price: 100, tax_rate: 0.08, discount_rate: 0.1 ) pricing_formulas = { discount: "base_price * discount_rate", discounted_price: "base_price - discount", tax: "discounted_price * tax_rate", total: "discounted_price + tax" } calculator.solve!(pricing_formulas) #=> {discount: 10.0, discounted_price: 90.0, tax: 7.2, total: 97.2} result = calculator.solve( a: "b + 1", b: "c + 1", c: "10" ) #=> {c: 10, b: 11, a: 12} result = calculator.solve( valid: "10 + 5", invalid: "missing_var + 1" ) #=> {valid: 15, invalid: :undefined} begin calculator.solve!( a: "b + 1", b: "a + 1" ) rescue TSort::Cyclic => e puts "Circular dependency detected!" end ``` -------------------------------- ### Finding Expression Dependencies with Dentaku's dependencies Source: https://context7.com/rubysolo/dentaku/llms.txt Explains the `dependencies` method, which analyzes formulas to identify all required variables for evaluation. It covers finding dependencies in simple and nested expressions, excluding variables already present in memory, and using dependencies for pre-evaluation validation. ```ruby calculator = Dentaku::Calculator.new calculator.dependencies("bob + dole / 3") #=> ["bob", "dole"] calculator.store(apples: 3) calculator.dependencies("apples + oranges") #=> ["oranges"] calculator.dependencies("a + b", a: 1) #=> ["b"] calculator.dependencies("CONCAT(first_name, ' ', last_name)") #=> ["first_name", "last_name"] calculator.dependencies("MAP(items, item, item.price * quantity)") #=> ["items", "quantity"] calculator.dependencies("IF(discount > 0, price * (1 - discount), price)") #=> ["discount", "price"] required = calculator.dependencies("total_cost / num_items") provided = { total_cost: 100 } missing = required - provided.keys.map(&:to_s) puts "Missing variables: #{missing}" #=> Missing variables: ["num_items"] ``` -------------------------------- ### Evaluate Expressions with Variable Binding Source: https://github.com/rubysolo/dentaku/blob/main/README.md Shows how to pass variable values during evaluation and how to configure case sensitivity for variable names. ```ruby calculator = Dentaku::Calculator.new calculator.evaluate('kiwi + 5', kiwi: 2) calculator = Dentaku::Calculator.new(case_sensitive: true) calculator.evaluate('Kiwi + 5', Kiwi: -2, kiwi: 2) ``` -------------------------------- ### Evaluate Mathematical and Logical Expressions in Ruby Source: https://context7.com/rubysolo/dentaku/llms.txt Demonstrates basic expression evaluation using the Calculator class, including arithmetic, variable injection, and strict vs. permissive error handling. ```ruby require 'dentaku' calculator = Dentaku::Calculator.new # Basic arithmetic calculator.evaluate('10 * 2') #=> 20 # With variables passed at evaluation time calculator.evaluate('kiwi + 5', kiwi: 2) #=> 7 # Strict evaluation raises exceptions begin calculator.evaluate!('10 * x') rescue Dentaku::UnboundVariableError => e puts "Missing variables: #{e.unbound_variables}" end ``` -------------------------------- ### Dentaku: Logical Operators (AND, OR) Source: https://context7.com/rubysolo/dentaku/llms.txt Shows how to use '&&' and '||' as aliases for logical AND and OR operations in Dentaku expressions. These are useful for combining multiple conditions. ```ruby calculator.evaluate('(a > 0) && (b > 0)', a: 1, b: 2) #=> true calculator.evaluate('(a > 10) || (b > 10)', a: 5, b: 15) #=> true ``` -------------------------------- ### Configure Calculator Behavior Source: https://context7.com/rubysolo/dentaku/llms.txt Explains how to toggle case sensitivity, disable nested data support for performance, and handle special characters in variable names using backticks. It also demonstrates the use of inline comments in expressions. ```ruby case_sensitive = Dentaku::Calculator.new(case_sensitive: true) fast_calc = Dentaku::Calculator.new(nested_data_support: false) calculator.evaluate('`my-variable` + 10', 'my-variable' => 5) calculator.evaluate('kiwi + 5 /* This adds 5 to kiwi */', kiwi: 2) ``` -------------------------------- ### CASE Statements for Conditional Logic in Dentaku Source: https://context7.com/rubysolo/dentaku/llms.txt Explains the CASE statement syntax for implementing multi-branch conditional logic, similar to SQL CASE expressions. It covers basic usage with variables, calculations within WHEN clauses, and nested CASE statements for complex scenarios. ```ruby calculator = Dentaku::Calculator.new calculator.evaluate('CASE x WHEN 1 THEN "one" WHEN 2 THEN "two" ELSE "other" END', x: 1) #=> "one" calculator.evaluate('CASE x WHEN 1 THEN "one" WHEN 2 THEN "two" ELSE "other" END', x: 2) #=> "two" calculator.evaluate('CASE x WHEN 1 THEN "one" WHEN 2 THEN "two" ELSE "other" END', x: 99) #=> "other" calculator.evaluate(' CASE fruit WHEN "apple" THEN 1 * quantity WHEN "banana" THEN 2 * quantity ELSE 3 * quantity END ', fruit: "banana", quantity: 5) #=> 10 calculator.evaluate(' CASE tier WHEN "bronze" THEN price * 1.0 WHEN "silver" THEN price * 0.9 WHEN "gold" THEN price * 0.8 ELSE price END ', tier: "gold", price: 100) #=> 80 calculator.evaluate(' ROUND( CASE category WHEN "electronics" THEN base_price * 1.15 WHEN "clothing" THEN base_price * 1.08 ELSE base_price * 1.05 END , 2) ', category: "electronics", base_price: 99.99) #=> 114.99 ``` -------------------------------- ### Perform Date and Time Arithmetic Source: https://context7.com/rubysolo/dentaku/llms.txt Shows how to store temporal data in the calculator and perform operations like date subtraction, adding durations, and comparing timestamps within formulas. ```ruby calculator = Dentaku::Calculator.new calculator.store(start_date: Date.new(2024, 1, 1), end_date: Date.new(2024, 12, 31)) # Arithmetic calculator.evaluate('end_date - start_date') calculator.evaluate('start_date + 30') # Time arithmetic calculator.store(event_time: Time.new(2024, 6, 15, 10, 0, 0)) calculator.evaluate('event_time + 1*24*60*60') ``` -------------------------------- ### Dentaku: String Search and Replace (FIND, SUBSTITUTE, CONTAINS) Source: https://context7.com/rubysolo/dentaku/llms.txt Details string searching and replacement functions in Dentaku. FIND locates substrings, SUBSTITUTE replaces them, and CONTAINS checks for their presence, all useful for text processing and validation. ```ruby calculator = Dentaku::Calculator.new # FIND - find position of substring (1-indexed, returns nil if not found) calculator.evaluate('FIND("World", "Hello World")') #=> 7 calculator.evaluate('FIND("xyz", "Hello World")') #=> nil # SUBSTITUTE - replace first occurrence calculator.evaluate('SUBSTITUTE("Hello World", "World", "Ruby")') #=> "Hello Ruby" # CONTAINS - check if substring exists calculator.evaluate('CONTAINS("World", "Hello World")') #=> true calculator.evaluate('CONTAINS("xyz", "Hello World")') #=> false ``` -------------------------------- ### Finding Expression Dependencies Source: https://context7.com/rubysolo/dentaku/llms.txt Explains the `dependencies` method for identifying variables required by an expression. ```APIDOC ## Finding Expression Dependencies ### Description The `dependencies` method analyzes formulas to find which variables are required for evaluation. ### Method - **`dependencies(expression, context = {})`**: Returns an array of variable names required by the expression. ### Parameters - **`expression`** (string) - The formula string to analyze. - **`context`** (Hash, optional) - A hash of pre-defined variables to exclude from the dependency list. ### Examples ```ruby calculator = Dentaku::Calculator.new # Find dependencies in simple expression calculator.dependencies("bob + dole / 3") #=> ["bob", "dole"] # Dependencies excludes variables already in memory calculator.store(apples: 3) calculator.dependencies("apples + oranges") #=> ["oranges"] # Dependencies with context calculator.dependencies("a + b", a: 1) #=> ["b"] # Dependencies in function arguments calculator.dependencies("CONCAT(first_name, ' ', last_name)") #=> ["first_name", "last_name"] # Dependencies in collection functions calculator.dependencies("MAP(items, item, item.price * quantity)") #=> ["items", "quantity"] # Dependencies in nested expressions calculator.dependencies("IF(discount > 0, price * (1 - discount), price)") #=> ["discount", "price"] # Use dependencies to validate before evaluation required = calculator.dependencies("total_cost / num_items") provided = { total_cost: 100 } missing = required - provided.keys.map(&:to_s) puts "Missing variables: #{missing}" #=> Missing variables: ["num_items"] ``` ``` -------------------------------- ### Dentaku: Collection Transformation (MAP) Source: https://context7.com/rubysolo/dentaku/llms.txt Demonstrates the MAP function for transforming each element in a collection (array) based on a provided expression. It takes a collection, an item identifier, and the transformation logic. ```ruby calculator = Dentaku::Calculator.new # MAP - transform each element # Syntax: MAP(collection, item_identifier, expression) calculator.evaluate('MAP(numbers, n, n * 2)', numbers: [1, 2, 3, 4, 5]) #=> [2, 4, 6, 8, 10] calculator.evaluate('MAP(prices, p, p * 1.1)', prices: [100, 200, 300]) #=> [110.0, 220.0, 330.0] ``` -------------------------------- ### Manage Formula Cache in Dentaku Source: https://context7.com/rubysolo/dentaku/llms.txt Demonstrates how to clear specific or all cached formulas and how to temporarily disable caching for specific evaluation blocks to ensure fresh calculations. ```ruby calculator.clear_cache('x + y') calculator.clear_cache(/tax/) calculator.clear_cache(:all) calculator.disable_cache do |calc| calc.evaluate('one_time_formula * x', one_time_formula: 123, x: 2) end ``` -------------------------------- ### Define Function Aliases and Internationalization Source: https://context7.com/rubysolo/dentaku/llms.txt Shows how to map standard function names to localized aliases, allowing expressions to be written in different languages. Aliases can be set globally or scoped to specific calculator instances for thread safety. ```ruby Dentaku.aliases = { round: ['arrondir', 'runden', 'округлить'] } french_calc = Dentaku::Calculator.new(aliases: { round: ['arrondir'], sum: ['somme'] }) french_calc.evaluate('SI(x > 10, "grand", "petit")', x: 15) ``` -------------------------------- ### CASE Statements Source: https://context7.com/rubysolo/dentaku/llms.txt Explains how to use CASE statements for conditional logic within formulas. ```APIDOC ## CASE Statements ### Description Provides multi-branch conditional logic similar to SQL CASE expressions. ### Syntax `CASE variable WHEN value1 THEN result1 WHEN value2 THEN result2 ELSE default_result END` ### Parameters - **variable** (any) - The variable or expression to evaluate. - **WHEN value THEN result** (pairs) - Conditions and their corresponding results. - **ELSE default_result** (any, optional) - The result if no WHEN condition is met. ### Examples ```ruby calculator = Dentaku::Calculator.new # Basic CASE syntax calculator.evaluate('CASE x WHEN 1 THEN "one" WHEN 2 THEN "two" ELSE "other" END', x: 1) #=> "one" calculator.evaluate('CASE x WHEN 1 THEN "one" WHEN 2 THEN "two" ELSE "other" END', x: 2) #=> "two" calculator.evaluate('CASE x WHEN 1 THEN "one" WHEN 2 THEN "two" ELSE "other" END', x: 99) #=> "other" # CASE with calculations calculator.evaluate('CASE fruit WHEN "apple" THEN 1 * quantity WHEN "banana" THEN 2 * quantity ELSE 3 * quantity END', fruit: "banana", quantity: 5) #=> 10 # CASE for pricing tiers calculator.evaluate('CASE tier WHEN "bronze" THEN price * 1.0 WHEN "silver" THEN price * 0.9 WHEN "gold" THEN price * 0.8 ELSE price END', tier: "gold", price: 100) #=> 80 # Nested CASE with other functions calculator.evaluate('ROUND(CASE category WHEN "electronics" THEN base_price * 1.15 WHEN "clothing" THEN base_price * 1.08 ELSE base_price * 1.05 END, 2)', category: "electronics", base_price: 99.99) #=> 114.99 ``` ``` -------------------------------- ### PLUCK and REDUCE Collection Functions in Dentaku Source: https://context7.com/rubysolo/dentaku/llms.txt Demonstrates the PLUCK function for extracting values from collections based on a key (with optional default values) and the REDUCE function for aggregating collection elements into a single value. These functions are essential for data manipulation within the Dentaku expression language. ```ruby users = [ { 'name' => 'Alice', 'age' => 30 }, { 'name' => 'Bob', 'age' => 25 }, { 'name' => 'Charlie', 'age' => 35 } ] calculator.evaluate('PLUCK(users, name)', users: users) #=> ["Alice", "Bob", "Charlie"] calculator.evaluate('PLUCK(users, age)', users: users) #=> [30, 25, 35] users_with_missing = [ { 'name' => 'Alice', 'role' => 'admin' }, { 'name' => 'Bob' } ] calculator.evaluate('PLUCK(users, role, "user")', users: users_with_missing) #=> ["admin", "user"] calculator.evaluate('REDUCE(numbers, sum, n, sum + n, 0)', numbers: [1, 2, 3, 4, 5]) #=> 15 calculator.evaluate('REDUCE(numbers, product, n, product * n, 1)', numbers: [1, 2, 3, 4]) #=> 24 ``` -------------------------------- ### Dentaku: Numeric Functions (SUM, MIN, MAX, AVG, COUNT, MUL, ABS, ROUND) Source: https://context7.com/rubysolo/dentaku/llms.txt Illustrates the usage of built-in numeric functions in Dentaku, including aggregation (SUM, MIN, MAX, AVG, COUNT, MUL), absolute value (ABS), and rounding functions (ROUND, ROUNDUP, ROUNDDOWN). These functions operate on numbers and arrays. ```ruby calculator = Dentaku::Calculator.new # SUM - variadic, accepts multiple arguments or array calculator.evaluate('SUM(1, 2, 3, 4, 5)') #=> 15 calculator.evaluate('SUM(values)', values: [10, 20, 30]) #=> 60 # MIN and MAX calculator.evaluate('MIN(5, 3, 8, 1)') #=> 1 calculator.evaluate('MAX(5, 3, 8, 1)') #=> 8 calculator.evaluate('MIN(prices)', prices: [99, 149, 79]) #=> 79 # AVG - average calculator.evaluate('AVG(10, 20, 30)') #=> 20 calculator.evaluate('AVG(scores)', scores: [85, 90, 95]) #=> 90 # COUNT calculator.evaluate('COUNT(1, 2, 3, 4, 5)') #=> 5 # MUL - multiply all arguments calculator.evaluate('MUL(2, 3, 4)') #=> 24 # ABS - absolute value calculator.evaluate('ABS(-42)') #=> 42 # ROUND, ROUNDUP, ROUNDDOWN calculator.evaluate('ROUND(8.2)') #=> 8 calculator.evaluate('ROUND(8.2759, 2)') #=> 8.28 calculator.evaluate('ROUNDUP(8.1)') # Ceiling #=> 9 calculator.evaluate('ROUNDDOWN(8.9)') # Floor #=> 8 ``` -------------------------------- ### Handle Evaluation Errors Source: https://github.com/rubysolo/dentaku/blob/main/README.md Demonstrates the difference between evaluate (returns nil on error) and evaluate! (raises an exception). ```ruby calculator = Dentaku::Calculator.new calculator.evaluate('10 * x') calculator.evaluate!('10 * x') ``` -------------------------------- ### Store Variables and Formulas in Calculator Memory Source: https://context7.com/rubysolo/dentaku/llms.txt Shows how to persist variables, nested hashes, arrays, and formulas within the calculator instance for reuse across multiple evaluations. ```ruby calculator = Dentaku::Calculator.new # Store single values calculator.store(peaches: 15) # Store nested hashes (dot notation access) calculator.store(user: { age: 25, salary: 50000 }) calculator.evaluate('user.age') #=> 25 # Store formulas for reuse calculator.store_formula('area', 'length * width') calculator.evaluate('area', length: 5, width: 10) #=> 50 ``` -------------------------------- ### Shorthand Global Functions Source: https://context7.com/rubysolo/dentaku/llms.txt Quick evaluation functions for one-off expressions without requiring a calculator instance. ```APIDOC ## POST /evaluate ### Description Evaluates a mathematical expression using global shorthand functions. ### Method POST ### Parameters #### Request Body - **expression** (string) - Required - The formula to evaluate. - **variables** (object) - Optional - Key-value pairs for variables used in the expression. - **strict** (boolean) - Optional - If true, uses Dentaku!() to raise errors instead of returning nil. ### Request Example { "expression": "price * qty", "variables": {"price": 9.99, "qty": 3}, "strict": true } ### Response #### Success Response (200) - **result** (any) - The evaluated result of the expression. ``` -------------------------------- ### Dentaku: Collection Filtering (FILTER) Source: https://context7.com/rubysolo/dentaku/llms.txt Explains the FILTER function, which selects elements from a collection that satisfy a given condition. It requires a collection, an item identifier, and the filtering condition. ```ruby calculator = Dentaku::Calculator.new # FILTER - select elements matching condition # Syntax: FILTER(collection, item_identifier, condition) calculator.evaluate('FILTER(numbers, n, n > 3)', numbers: [1, 2, 3, 4, 5]) #=> [4, 5] calculator.evaluate('FILTER(ages, a, a >= 18)', ages: [15, 18, 21, 16, 25]) #=> [18, 21, 25] ``` -------------------------------- ### Cache Management Source: https://context7.com/rubysolo/dentaku/llms.txt Methods for managing the internal formula cache to optimize performance and memory usage. ```APIDOC ## POST /calculator/clear_cache ### Description Clears specific or all entries from the calculator's formula cache. ### Method POST ### Parameters #### Request Body - **pattern** (string/regex/symbol) - Required - The formula string, regex pattern, or :all to clear the cache. ### Request Example { "pattern": "x + y" } ### Response #### Success Response (200) - **status** (string) - Confirmation of cache clearance. ``` -------------------------------- ### Store Variables in Calculator Memory Source: https://github.com/rubysolo/dentaku/blob/main/README.md Explains how to persist variable values within the calculator instance for subsequent evaluations. ```ruby calculator = Dentaku::Calculator.new calculator.store(peaches: 15) calculator.evaluate('peaches - 5') calculator.evaluate('peaches >= 15') ``` -------------------------------- ### Solving Systems of Dependent Formulas Source: https://context7.com/rubysolo/dentaku/llms.txt Details the `solve!` and `solve` methods for evaluating formulas with interdependencies. ```APIDOC ## Solving Systems of Dependent Formulas ### Description The `solve!` and `solve` methods automatically resolve dependencies between formulas using topological sorting. ### Methods - **`solve!(formulas)`**: Evaluates formulas, raising an error for circular dependencies. - **`solve(formulas)`**: Evaluates formulas, returning `:undefined` for problematic or missing dependencies. ### Parameters - **`formulas`** (Hash) - A hash where keys are variable names and values are formula strings. ### Examples ```ruby calculator = Dentaku::Calculator.new # Basic dependency resolution calculator.store(monthly_income: 5000) frmls = { annual_income: "monthly_income * 12", income_taxes: "annual_income * 0.25", net_income: "annual_income - income_taxes" } results = calculator.solve!(frmls) #=> {annual_income: 60000, income_taxes: 15000.0, net_income: 45000.0} # Complex interdependent formulas calculator.store( base_price: 100, tax_rate: 0.08, discount_rate: 0.1 ) pricing_formulas = { discount: "base_price * discount_rate", discounted_price: "base_price - discount", tax: "discounted_price * tax_rate", total: "discounted_price + tax" } calculator.solve!(pricing_formulas) #=> {discount: 10.0, discounted_price: 90.0, tax: 7.2, total: 97.2} # solve (without !) returns :undefined for problematic formulas result = calculator.solve( a: "b + 1", b: "c + 1", c: "10" ) #=> {c: 10, b: 11, a: 12} # With missing dependencies - permissive mode result = calculator.solve( valid: "10 + 5", invalid: "missing_var + 1" ) #=> {valid: 15, invalid: :undefined} # solve! raises on circular dependencies begin calculator.solve!( a: "b + 1", b: "a + 1" ) rescue TSort::Cyclic => e puts "Circular dependency detected!" end ``` ``` -------------------------------- ### Handle Evaluation Errors Source: https://context7.com/rubysolo/dentaku/llms.txt Provides patterns for catching specific exceptions like UnboundVariableError, ParseError, and ZeroDivisionError. It also demonstrates using the solve method with a block to handle errors gracefully during batch evaluations. ```ruby begin calculator.evaluate!('10 / 0') rescue Dentaku::ZeroDivisionError puts "Division by zero!" end # Batch solve with error handling results = calculator.solve(valid: "10 + 5", divzero: "1 / 0") do |error| error.is_a?(Dentaku::ZeroDivisionError) ? 0 : :error end ``` -------------------------------- ### Add Custom External Functions - Ruby Source: https://github.com/rubysolo/dentaku/blob/main/README.md Extends the calculator's functionality by adding custom functions at runtime. Functions are defined with a name, return type, and a lambda that performs the calculation. Supports variadic functions. ```ruby > c = Dentaku::Calculator.new > c.add_function(:pow, :numeric, ->(mantissa, exponent) { mantissa ** exponent }) > c.evaluate('POW(3,2)') #=> 9 > c.evaluate('POW(2,3)') #=> 8 > c = Dentaku::Calculator.new > c.add_function(:max, :numeric, ->(*args) { args.max }) > c.evaluate 'MAX(8,6,7,5,3,0,9)' #=> 9 ``` -------------------------------- ### Error Handling Source: https://context7.com/rubysolo/dentaku/llms.txt Strategies for handling various exceptions during formula evaluation. ```APIDOC ## POST /evaluate/batch ### Description Solves multiple formulas at once with custom error handling logic for specific exception types. ### Method POST ### Parameters #### Request Body - **formulas** (object) - Required - Map of variable names to formula strings. ### Request Example { "formulas": { "valid": "10 + 5", "divzero": "1 / 0" } } ### Response #### Success Response (200) - **results** (object) - Map of variable names to evaluated results or handled error values. ``` -------------------------------- ### Define Function Aliases - Ruby Source: https://github.com/rubysolo/dentaku/blob/main/README.md Creates aliases for existing functions to support multilingual expressions or custom naming conventions. Aliases can be set globally or provided during calculator initialization for thread-safe usage. ```ruby Dentaku.aliases = { round: ['rrrrround!', 'округлить'] } Dentaku('rrrrround!(8.2) + округлить(8.4)') # the same as round(8.2) + round(8.4) # 16 aliases = { round: ['rrrrround!', 'округлить'] } c = Dentaku::Calculator.new(aliases: aliases) c.evaluate('rrrrround!(8.2) + округлить(8.4)') # 16 ``` -------------------------------- ### Solve Formulas with Dependency Resolution - Ruby Source: https://github.com/rubysolo/dentaku/blob/main/README.md Automatically determines the evaluation order for a set of formulas using TSort. It resolves dependencies and returns a hash of computed values. Raises TSort::Cyclic for circular dependencies or other errors during evaluation. ```ruby calc = Dentaku::Calculator.new calc.store(monthly_income: 50) need_to_compute = { income_taxes: "annual_income / 5", annual_income: "monthly_income * 12" } calc.solve!(need_to_compute) #=> {annual_income: 600, income_taxes: 120} calc.solve!( make_money: "have_money", have_money: "make_money" ) #=> raises TSort::Cyclic ``` -------------------------------- ### Evaluate Expressions with Inline Comments - Ruby Source: https://github.com/rubysolo/dentaku/blob/main/README.md Evaluates a mathematical expression that may contain inline comments. Comments, whether single or multi-line, are ignored during evaluation. This is useful for documenting complex formulas directly within the expression. ```ruby calculator.evaluate('kiwi + 5 /* This is a comment */', kiwi: 2) #=> 7 /* * This is a multi-line comment */ /* This is another type of multi-line comment */ ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.