식트리란?
식을 트리로 표현한 자료구조
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp16
{
class Program
{
static void Main(string[] args)
{
/* 식트리 */
//1*2+(x-y)
Expression const1 = Expression.Constant(1);
Expression const2 = Expression.Constant(2);
Expression leftExp = Expression.Multiply(const1, const2); //1*2
Expression param1 =
Expression.Parameter(typeof(int)); //x를 위한변수
Expression param2 =
Expression.Parameter(typeof(int));//y를 위한 변수
Expression rightExp = Expression.Subtract(param1,param2); //x-y
Expression exp = Expression.Add(leftExp, rightExp);
Expression> expression =
Expression>.Lambda>(
exp, new ParameterExpression[]
{ (ParameterExpression)param1,
(ParameterExpression)param2 });
Func func = expression.Compile(); //실행 가능한 코드로 컴파일
//X=7,Y=8
Console.WriteLine($"1*2+({7}-{8})={func(7, 8)}"); //컴파일한 무명함수 실행
//람다식을 이용해 식트리를 만드는 예) 위와 동일한 실행결과
Expression> ex =
(a, b) => 1 * 2 + (a - b);
Func func1 = expression.Compile();
Console.WriteLine($"1*2+({7}-{8})={func1(7, 8)}");
}
}
}
'코딩연습 > C#' 카테고리의 다른 글
| [C#]문자열을 입력받아 아스키코드로 분류 (0) | 2020.06.16 |
|---|---|
| [C#]람다식을 이용하여 계산기 클래스 만들기 (0) | 2020.06.15 |
| [C#]람다식(Action대리자 (0) | 2020.06.15 |
| [C#]람다식(Func대리자) (0) | 2020.06.15 |
| [C#]LINQ연습문제(레코드조회) (0) | 2020.06.12 |