Statement vs Expression
Tech 2008/07/22 11:54C/C++ 에서는 대입문 - 이 사실 문(statement)이 아니라 식(expression)이다. 따라서 다음 코드가 동작한다.
#include <stdio.h>
int main() {
int x = 10;
printf("%d\n", x = 20);
return 0;
}
실행하면 20 이란는 숫자가 콘솔에 찍힌다. 파이썬에서는 대입문이 맞다. 따라서
print x=10
이런 파이썬 코드는 유효하지 않다. 별 생각 없이 쓰고 있었는데, 파이썬에 대해 아무것도 모르고 있었구나 -_-; ... 뿐 아니라 프로그래밍 언어 자체에 대해 기초가 부족했다. 아 뼈아퍼라...
사실, 문과 식을 구분해서 쓰는 사람이 그다지 많지는 않다(고 느낀다). 나도 가끔 필요할 때만 확인해보곤 하는데 ... 자, 정확히 statement, expression 이 무엇인지 설명한다면? 이라고 하니까 바로 답이 튀어나오지 않는다. 그래서 위키에서 긁어왔다.
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements. A statement will have internal components (eg, expressions). - From wikipedia
An expression in a programming language is a combination of values, variables, operators, and functions that are interpreted (evaluated) according to the particular rules of precedence and of association for a particular programming language, which computes and then produces (returns, in a stateful environment) another value. The expression is said to evaluate to that value. As in mathematics, the expression is (or can be said to have) its evaluated value; the expression is a representation of that value. - From wikipedia
그냥 개인적인 생각이지만, 해보면 쉽다 쉽다 - 하는 함수형 언어를 사람들이 처음 접할때 많이 좌절하곤 하는데 그 이유가 이게 아닐까 한다. Imperative language에 익숙한 상황에서는 statement 의 나열로 문제를 해결하려고 하기 쉬운데, Functional language에서는 그게 쉽지 않다 - 기 보다는 제한적이거나 불가한 경우도 있다. 함수형 언어를 써보면 새로운 접근 방식을 익히게 된다고 하는데, 그 새로운 접근이 뭐냐? 라고 물으면 좀 난감했는데, 일단 이렇게 정리해볼 수 있으려나?
Expression oriented problem solving
Expression은 side-effect가 있을 수도 있고, 없을 수도 있다 - 고 한다. 이에 반해 Statement는 Side-effect를 만들어내기 위한 것이라고도 하는데 (statements do not return results and are executed solely for their side effects, - From wikipedia), side-effect를 지향/지양 하는 정도에 따라서도 접근이 달라질 수 있는 것 같다.
역시 기본부터 차근차근 다져야 하는데, 이런것도 확실히 정리 안해두고 코드를 만지고 있었다니 부끄럽다. :'( 일단 낙서 종료.
side-effect, referential transparency 등에 대해서도 살짝 정리해둬야겠다.
'Tech' 카테고리의 다른 글
| Spiral number galaxy (4) | 2008/08/09 |
|---|---|
| 투명 필름 문제(Scheme) (3) | 2008/08/01 |
| Statement vs Expression (3) | 2008/07/22 |
| emacs: switch indentation (0) | 2008/07/18 |
| 방법당하다 by python-mysqldb 1.2.1_p2 (5) | 2008/06/11 |
| Troubleshooting: apt-get update -> Dynamic MMap out of room (0) | 2008/06/05 |

