성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Roll A Lisp In C - Reading ; https...
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>Python의 생성기와 코루틴을 C#으로 표현하면.</h1> <p> <br /> 요즘 이 책을 재미있게 보고 있습니다. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Programming Insight 파이썬 완벽 가이드 ; <a target='tab' href='http://www.yes24.com/24/goods/6694057'>http://www.yes24.com/24/goods/6694057</a> </pre> <br /> 그중에서 코루틴에 대한 이야기가 재미있습니다. 언어 간의 비교를 해보면 이해도를 높일 수 있고 서로 간의 장단점도 쉽게 파악이 되지요. ^^ 그래서 C#으로 한번 표현을 해봤습니다.<br /> <br /> 우선, 파이썬에서 yield를 이용한 구문 중에서 코루틴보다 간단한 생성기(generator)에 대한 예제를 먼저 보겠습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > def countdown(n): while n > 0: yield n n -= 1 for i in countdown(5): print i </pre> <br /> 이건 좀 쉽습니다. ^^ C#에서도 역시 yield 키워드를 이용해서 다음과 같이 만들어 볼 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > class Program { static void Main(string[] args) { Program inst = new Program(); foreach (var item in inst.CountDown(5)) { Console.WriteLine(item); } } <span style='color: blue; font-weight: bold'>IEnumerable<int></span> CountDown(int maxValue) { while (maxValue > 0) { <span style='color: blue; font-weight: bold'>yield return</span> maxValue --; } } } </pre> <br /> 부수적인 코드들이 들어갈 뿐 구조상으로 보면 파이썬의 표현과 거의 1:1 매핑이 됩니다.<br /> <br /> 다음으로 파이썬의 코루틴입니다. <br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > def print_matches(matchtext): print "Looking for", matchtext while True: <span style='color: blue; font-weight: bold'>line = (yield)</span> if matchtext in line: print line matcher = print_matches("python") matcher.next() matcher.send("Hello World") matcher.send("python is cool") matcher.close() // 출력 결과 Looking for python python is cool </pre> <br /> 대강 어떤 식인지 눈에 보이시죠? matcher.send의 인자로 입력된 것이 print_matches 함수의 (yield) 문의 결과로 반환되어 식이 평가되고 있는 것입니다.<br /> <br /> 요건 C#으로 옮기기에 그다지 멋있게 되지는 않지만, 다음과 같이 가능은 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > class Program { static void Main(string[] args) { Program inst = new Program(); inst.print_matches("python"); inst.send("Hello World"); inst.send("python is cool"); } string _matchText; string _message; IEnumerator<int> iter; void print_matches(string matchtext) { Console.WriteLine("Looking for: " + matchtext); _matchText = matchtext; iter = iterator().GetEnumerator(); iter.MoveNext(); } public void send(string message) { _message = message; iter.MoveNext(); } IEnumerable<int> iterator() { yield return 0; while (true) { if (_matchText.IndexOf(_message) == -1) { yield return 0; } Console.WriteLine(_message); yield return 1; } } } </pre> <br /> 음... 다소 억지스러운가요? ^^ 그나저나... 파이썬이라... 마음에 듭니다. ^^<br /> <br /> (<a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=745&boardid=331301885'>예제 코드는 첨부</a>해 두었습니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1857
(왼쪽의 숫자를 입력해야 합니다.)