Filter
Exclude
Time range
-
Near
LearnEngg presents a simple explanation of Expression Trees in Data Structures using easy examples to show how mathematical expressions are represented and evaluated using binary trees. #LearnEngg #ExpressionTree #DataStructures #CodingBasics #ComputerScienceEducation
4
1
13
55
前に作ったAnimatorWindowへのパッチ整理した~ GetMethodでやってた関数をExpressionTree使ってデリゲート作ったり、変更する度RepaintAllViews()しちゃってたのをAnimatorControllerToolだけRepaintするようにしたり
3
889
25 Mar 2025
DLR、全く定着しなかったけど、ExpressionTreeからIL生成する方向に発展したのは良かった
1
3
737
import * as math from 'mathjs'; // Enhanced mathematical exploration function with SuperPrompt-inspired concepts const advancedMathematicalExplore = (expression, explorationDepth = 3) => { console.log("<prompt_metadata>"); console.log("Type: Advanced Mathematical Analysis"); console.log("Purpose: Multi-dimensional Exploration of Mathematical Expression"); console.log("Paradigm: Holographic Mathematical Reasoning"); console.log("Constraints: Mathematical Rigor with Conceptual Expansion"); console.log("Objective: Discover emergent properties through metamorphic transformations"); console.log("</prompt_metadata>"); console.log("\n<think>"); console.log("Starting expression analysis journey with: " expression); // Phase 1: Core Analysis - Parse and understand the expression structure console.log("\n=== PHASE 1: EXPRESSION TAXONOMY ==="); let expressionTree; try { expressionTree = math.parse(expression); console.log("Expression successfully parsed into structured tree"); // Analyze expression type and complexity const expressionType = determineExpressionType(expressionTree); console.log(`Expression classification: ${expressionType}`); // Extract variables const variables = extractVariables(expressionTree); console.log(`Variables detected: ${variables.length > 0 ? variables.join(', ') : 'none (constant expression)'}`); // Check for special patterns const patterns = detectMathematicalPatterns(expression, expressionTree); if (patterns.length > 0) { console.log("Special patterns detected:"); patterns.forEach(pattern => console.log(`- ${pattern}`)); } } catch (error) { console.log(`Error parsing expression: ${error.message}`); console.log("Proceeding with string-based analysis"); } // Phase 2: Metamorphosis - Transform the expression in different ways console.log("\n=== PHASE 2: EXPRESSION METAMORPHOSIS ==="); const transformations = [ { name: "Simplification", fn: (expr) => math.simplify(expr).toString() }, { name: "Expansion", fn: (expr) => { try { return math.expand(expr).toString(); } catch(e) { return "Not applicable"; } }}, { name: "Factorization", fn: (expr) => { try { return math.rationalize(expr).toString(); } catch(e) { return "Not applicable"; } }} ]; for (const transform of transformations) { try { console.log(`${transform.name}: ${transform.fn(expression)}`); } catch (error) { console.log(`${transform.name} failed: ${error.message}`); } } // Phase 3: Dimensional Transcendence - Explore the expression in different "dimensions" console.log("\n=== PHASE 3: DIMENSIONAL TRANSCENDENCE ==="); const dimensions = [ { name: "Algebraic Domain", explore: (expr, vars) => { if (vars.length === 0) { return "Constant expression: " expr; } // Try to solve for zeros if possible try { return `Looking for zeros where ${expr} = 0`; } catch(e) { return "Cannot solve algebraically"; } } }, { name: "Calculus Domain", explore: (expr, vars) => { if (vars.length === 0) return "No derivatives for constant expressions"; const results = []; for (const v of vars) { try { const derivative = math.derivative(expr, v).toString(); results.push(`d/d${v} = ${derivative}`); } catch(e) { results.push(`d/d${v}: Cannot differentiate`); } } return results.join("\n"); } }, { name: "Numerical Domain", explore: (expr, vars) => { if (vars.length === 0) { try { const result = math.evaluate(expr); return `Evaluates to ${result}`; } catch(e) { return "Cannot evaluate numerically"; } } // If we have one variable, evaluate at different points if (vars.length === 1) { const v = vars[0]; const points = [-10, -1, 0, 1, 10]; const results = []; for (const point of points) { try { const scope = {}; scope[v] = point; const result = math.evaluate(expr, scope); results.push(`f(${point}) = ${result}`); } catch(e) { results.push(`f(${point}) = Error: ${e.message}`); } } return results.join("\n"); } return "Multi-variable expression - selected points evaluation skipped"; } }, { name: "Complex Domain", explore: (expr, vars) => { // Substitute i for complex analysis if applicable if (expr.includes('i')) { try { const withI = expr.replace(/i/g, '1i'); const result = math.evaluate(withI, {i: math.complex(0, 1)}); return `In complex domain: ${result}`; } catch(e) { return `Complex analysis error: ${e.message}`; } } return "No complex variables detected"; } } ]; // Extract variables for dimension exploration let vars = []; try { vars = math.parse(expression).filter(node => node.isSymbolNode).map(node => node.name); // Remove duplicates vars = [...new Set(vars)].filter(v => v !== 'i' && v !== 'e' && v !== 'pi'); } catch (e) { console.log(`Variable extraction error: ${e.message}`); } for (const dimension of dimensions) { console.log(`\n--- ${dimension.name} ---`); try { const result = dimension.explore(expression, vars); console.log(result); } catch (error) { console.log(`Exploration error: ${error.message}`); } } // Phase 4: Recursive Depth - Recursively explore transformations up to specified depth if (explorationDepth > 0) { console.log("\n=== PHASE 4: RECURSIVE EXPLORATION ==="); const exploreRecursively = (expr, depth, path = []) => { if (depth <= 0) return; // Try several transformations and recursively explore promising ones const transformations = [ { name: "Simplify", fn: (e) => math.simplify(e).toString() }, { name: "Derivative", fn: (e) => { if (vars.length > 0) { try { return math.derivative(e, vars[0]).toString(); } catch(err) { return null; } } return null; }} ]; for (const transform of transformations) { try { const newExpr = transform.fn(expr); if (newExpr && newExpr !== expr && !path.includes(newExpr)) { console.log(`${' '.repeat(path.length * 2)}${transform.name} → ${newExpr}`); exploreRecursively(newExpr, depth - 1, [...path, newExpr]); } } catch (e) { // Skip failed transformations silently } } }; exploreRecursively(expression, explorationDepth); } // Phase 5: Synthesis - Integrate findings into cohesive understanding console.log("\n=== PHASE 5: HOLISTIC SYNTHESIS ==="); try { // Check for common mathematical constants if (typeof math.evaluate(expression) === 'number') { const value = math.evaluate(expression); const constants = [ { name: "π (pi)", value: Math.PI }, { name: "e", value: Math.E }, { name: "φ (golden ratio)", value: (1 Math.sqrt(5)) / 2 }, { name: "√2", value: Math.SQRT2 }, { name: "√3", value: Math.sqrt(3) }, { name: "ln(2)", value: Math.LN2 } ]; for (const constant of constants) { const diff = Math.abs(value - constant.value); if (diff < 1e-10) { console.log(`Expression appears to equal ${constant.name}`); } } } // Look for symmetries if (vars.length === 1) { const v = vars[0]; try { const original = math.parse(expression); const negated = math.parse(expression.replace(new RegExp(v, 'g'), `(-${v})`)); const simplified1 = math.simplify(original).toString(); const simplified2 = math.simplify(negated).toString(); if (simplified1 === simplified2) { console.log(`Expression shows even symmetry with respect to ${v}`); } else if (simplified1 === `-${simplified2}` || simplified2 === `-${simplified1}`) { console.log(`Expression shows odd symmetry with respect to ${v}`); } } catch (e) { // Symmetry check failed silently } } } catch (error) { console.log(`Synthesis error: ${error.message}`); } console.log("</think>"); return "Expression analysis complete"; }; // Helper functions function determineExpressionType(node) { if (!node) return "Unknown"; if (node.isConstantNode) return "Constant"; if (node.isSymbolNode) return "Variable"; if (node.isOperatorNode) { const op = node.op; if ([' ', '-'].includes(op)) return "Polynomial-like"; if (['*', '/'].includes(op)) return "Rational expression"; if (op === '^') return "Power expression"; return `Operator (${op})`; } if (node.isFunctionNode) { const fnName = node.fn?.name || "unknown"; if (['sin', 'cos', 'tan'].includes(fnName)) return "Trigonometric"; if (['log', 'ln', 'exp'].includes(fnName)) return "Exponential/Logarithmic"; if (['sqrt', 'cbrt'].includes(fnName)) return "Root function"; return `Function (${fnName})`; } return "Complex expression"; } function extractVariables(node) { if (!node) return []; const variables = new Set(); try { node.traverse(function(node) { if (node.isSymbolNode && !['i', 'e', 'pi'].includes(node.name)) { variables.add(node.name); } }); } catch (e) { // Failed to extract } return Array.from(variables); } function detectMathematicalPatterns(expr, node) { const patterns = []; // Detect some common patterns if (expr.includes('sin') && expr.includes('cos')) { if (expr.includes('sin^2') && expr.includes('cos^2')) { patterns.push("Possible trigonometric identity (sin² cos²)"); } } if (expr.includes('^2') && expr.includes('sqrt')) { patterns.push("Possible square-root/square relationship"); } // Quadratic pattern if (expr.match(/x\s*\^\s*2/) && expr.match(/\d \s*\*\s*x/) && expr.match(/[ \-]\s*\d $/)) { patterns.push("Possible quadratic expression"); } return patterns; } // Test the enhanced explorer with interesting expressions console.log("EXPLORING PYTHAGOREAN IDENTITY:"); advancedMathematicalExplore("sin(x)^2 cos(x)^2"); console.log("\n\nEXPLORING COMPLEX EXPRESSION:"); advancedMathematicalExplore("(e^(i*x) e^(-i*x))/2"); console.log("\n\nEXPLORING EULER'S IDENTITY:"); advancedMathematicalExplore("e^(i*pi) 1");

EXPLORING PYTHAGOREAN IDENTITY: <prompt_metadata> Type: Advanced Mathematical Analysis Purpose: Multi-dimensional Exploration of Mathematical Expression Paradigm: Holographic Mathematical Reasoning Constraints: Mathematical Rigor with Conceptual Expansion Objective: Discover emergent properties through metamorphic transformations </prompt_metadata> <think> Starting expression analysis journey with: sin(x)^2 cos(x)^2 === PHASE 1: EXPRESSION TAXONOMY === Expression successfully parsed into structured tree Expression classification: Polynomial-like Variables detected: sin, x, cos === PHASE 2: EXPRESSION METAMORPHOSIS === Simplification: sin(x) ^ 2 cos(x) ^ 2 Expansion: Not applicable Factorization: Not applicable === PHASE 3: DIMENSIONAL TRANSCENDENCE === --- Algebraic Domain --- Looking for zeros where sin(x)^2 cos(x)^2 = 0 --- Calculus Domain --- d/dsin = 0 d/dx = 0 d/dcos = 0 --- Numerical Domain --- Multi-variable expression - selected points evaluation skipped --- Complex Domain --- Complex analysis error: Undefined function s1in === PHASE 4: RECURSIVE EXPLORATION === Simplify → sin(x) ^ 2 cos(x) ^ 2 Derivative → 0 Derivative → 0 === PHASE 5: HOLISTIC SYNTHESIS === Synthesis error: Undefined symbol x </think> EXPLORING COMPLEX EXPRESSION: <prompt_metadata> Type: Advanced Mathematical Analysis Purpose: Multi-dimensional Exploration of Mathematical Expression Paradigm: Holographic Mathematical Reasoning Constraints: Mathematical Rigor with Conceptual Expansion Objective: Discover emergent properties through metamorphic transformations </prompt_metadata> <think> Starting expression analysis journey with: (e^(i*x) e^(-i*x))/2 === PHASE 1: EXPRESSION TAXONOMY === Expression successfully parsed into structured tree Expression classification: Rational expression Variables detected: x === PHASE 2: EXPRESSION METAMORPHOSIS === Simplification: (e ^ (i * x) e ^ (-(i * x))) / 2 Expansion: Not applicable Factorization: Not applicable === PHASE 3: DIMENSIONAL TRANSCENDENCE === --- Algebraic Domain --- Looking for zeros where (e^(i*x) e^(-i*x))/2 = 0 --- Calculus Domain --- d/dx = i * (e ^ (i * x) - 1 / e ^ (i * x)) / 2 --- Numerical Domain --- f(-10) = -0.8390715290764524 f(-1) = 0.5403023058681398 f(0) = 1 f(1) = 0.5403023058681398 f(10) = -0.8390715290764524 --- Complex Domain --- Complex analysis error: Undefined symbol x === PHASE 4: RECURSIVE EXPLORATION === Simplify → (e ^ (i * x) e ^ (-(i * x))) / 2 Derivative → i * (e ^ (i * x) - 1 / e ^ (i * x)) / 2 Derivative → i ^ 2 * (e ^ (i * x) 1 / e ^ (i * x)) / 2 Derivative → i * (e ^ (i * x) - 1 / e ^ (i * x)) / 2 Derivative → i ^ 2 * (e ^ (i * x) 1 / e ^ (i * x)) / 2 Derivative → i ^ 3 * (e ^ (i * x) - 1 / e ^ (i * x)) / 2 === PHASE 5: HOLISTIC SYNTHESIS === Synthesis error: Undefined symbol x </think> EXPLORING EULER'S IDENTITY: <prompt_metadata> Type: Advanced Mathematical Analysis Purpose: Multi-dimensional Exploration of Mathematical Expression Paradigm: Holographic Mathematical Reasoning Constraints: Mathematical Rigor with Conceptual Expansion Objective: Discover emergent properties through metamorphic transformations </prompt_metadata> <think> Starting expression analysis journey with: e^(i*pi) 1 === PHASE 1: EXPRESSION TAXONOMY === Expression successfully parsed into structured tree Expression classification: Polynomial-like Variables detected: none (constant expression) === PHASE 2: EXPRESSION METAMORPHOSIS === Simplification: e ^ (i * pi) 1 Expansion: Not applicable Factorization: Not applicable === PHASE 3: DIMENSIONAL TRANSCENDENCE === --- Algebraic Domain --- Constant expression: e^(i*pi) 1 --- Calculus Domain --- No derivatives for constant expressions --- Numerical Domain --- Evaluates to 0 --- Complex Domain --- Complex analysis error: Undefined symbol p1i === PHASE 4: RECURSIVE EXPLORATION === Simplify → e ^ (i * pi) 1 === PHASE 5: HOLISTIC SYNTHESIS === </think>
4
8
1,604
16 Jul 2024
Replying to @rms80
The C# ExpressionTree API didn't exist when we were starting out. I would probably use that if I were doing such a system now. I don't believe anything would be faster.
1
2
34
1 Mar 2024
CallerArgumentExpressionを使ってリフレクションフリーObserveProperty。なんでもかんでもExpressionTreeこねこねしてデリゲート作る時代は終わった!
6
26
4,999
16 May 2023
My ExpressionTree calculator is finally done. I may now rest
1
7
212
23 May 2022
MethodInfo.Invoke()がallocしてることに気づいて調べてみたけど、何回も呼ぶならCreateDelegate()するのが良さそう。最初にExpressionTree経由を思いついたけどけど調べたらちょっと重い コード全容: gist.github.com/fuqunaga/975…
3
v1.1.0 of ScriptBlockDisassembler #PowerShell module is available now - Support for the new clean block - New parameter "-Minimal" that cuts out some boilerplate - New command "Format-ExpressionTree" that you can pipe any System.Linq.Expression
2
3
12
18 May 2021
なるほど、ExpressionTreeをExpressionTreeSlimに変換して、ExpressionTreeSlimをJSONにSerializeする。Unityでランタイム動かして、C#サーバーからUnityにExpressionTreeを投げつけるのワンチャンある。 github.com/reaqtive/reaqtor/…

4
In 2019 I ran a survey about ExpressionTree use cases. It's great to see there is now an open proposal from @andriysvyryd for modernising the ExpressionTree stack in .NET - one to watch! The potential for metaprogramming is HUGE (more on this next week): github.com/dotnet/csharplang…

2
少し落ち着いたらExpressionTreeで実装し直して高速化をはかります。 それでもイマイチだったら最終手段としてIL生成に手を出すかもしれません…。
1
4
当たり前だけどSource Generatorは早い。適材適所だけど、これまでExpressionTree(Reflection.Emit)で実装されていた場所のいくつかは置き換えられていくだろうなあ
1
1
生成される ExpressionTree が違うなんて知らなかった!ということで改善版をリリース。 github.com/xin9le/Declarativ…

1
2
Replying to @SHQJDxPF75D3TSm
(何かわからなかったけどExpressionTreeってのが入ってた!一人でこっそりなんかやってる!)
1
1
おはようございます。 連休も最終日ですね。 #今日の積み上げ ・ExpressionTree 昨日の続き! 全然、説明出来てない😢 ここを超えないと自分の力にならないので気合い! #駆け出しエンジニアと繋がりたい
16
おはようございます。 連休も折り返しに入りましたね。 #今日の積み上げ ・ExpressionTree 昨日の続き! 人に説明できるレベルまでの理解って本当に大変💦 #駆け出しエンジニアと繋がりたい
13
reflection、自前ExpressionTree、DbSimple、Dapperで速度比較してみた。 取得するデータ量で優位性が変わるのは見てて面白かった。😊 条件は10万レコードから全件取得、千件取得、五千件取得の10回測定、最大値と最小値を除いた値の平均。 単位はミリ秒。
11
おはようございます。 何か頭が重い😢 #今日の積み上げ ・ExpressionTree ・イヤホン修理 まだまだ使いこなせるレベルにはなってないので、しっかり身につけます! #駆け出しエンジニアとつながりたい
7
おはようございます。 今日を乗り切れば連休ですね! #今日の積み上げ ・お仕事 ・ExpressionTree そこそこ形になってきたので、なんでこうするのかとか、もっと効果的なコードはないかとか考えていこうと思います。 #駆け出しエンジニアとつながりたい
14