Mathematica : 기호 프로그래밍이란 무엇입니까?
나는 Stephen Wolfram의 열렬한 팬이지만 그는 분명히 자신의 경적을 너무 부끄럽지 않은 사람입니다. 많은 참고 문헌에서 그는 Mathematica를 다른 상징적 프로그래밍 패러다임으로 칭찬합니다. 저는 Mathematica 사용자가 아닙니다.
내 질문은 다음과 같습니다.이 상징적 프로그래밍은 무엇입니까? 기능적 언어 (예 : Haskell)와 어떻게 비교됩니까?
Mathematica의 기호 프로그래밍은 검색 및 바꾸기 규칙을 지정하여 프로그래밍하는 검색 및 바꾸기 시스템으로 생각할 수 있습니다.
예를 들어 다음 규칙을 지정할 수 있습니다.
area := Pi*radius^2;
다음에을 사용하면 area
으로 대체됩니다 Pi*radius^2
. 이제 새 규칙을 정의한다고 가정합니다.
radius:=5
당신이 사용할 때마다 지금 radius
, 그것은으로 다시거야 5
. 평가 area
하면 Pi*radius^2
재 작성 규칙을 트리거하는 항목이 재 작성되고 중간 결과를 radius
얻을 수 Pi*5^2
있습니다. 이 새 양식은 ^
작업 에 대한 기본 제공 다시 쓰기 규칙을 트리거 하므로식이 Pi*25
. 이 시점에서 적용 가능한 규칙이 없기 때문에 다시 쓰기가 중지됩니다.
대체 규칙을 함수로 사용하여 함수형 프로그래밍을 에뮬레이트 할 수 있습니다. 예를 들어, 추가하는 함수를 정의하려면 다음을 수행 할 수 있습니다.
add[a_,b_]:=a+b
지금 add[x,y]
으로 다시 작성됩니다 x+y
. 숫자 a, b에만 적용하도록 추가하려면 대신 할 수 있습니다.
add[a_?NumericQ, b_?NumericQ] := a + b
이제 규칙 add[2,3]
을 2+3
사용하여 다시 작성된 다음에 5
대한 기본 제공 규칙 을 사용하도록 다시 작성 +
되지만 add[test1,test2]
변경되지 않은 상태로 유지됩니다.
다음은 대화 형 대체 규칙의 예입니다.
a := ChoiceDialog["Pick one", {1, 2, 3, 4}]
a+1
여기서는으로 a
바뀌고 ChoiceDialog
팝업 된 대화 상자에서 사용자가 선택한 숫자로 대체되어 수량을 모두 숫자로 만들고 대체 규칙을 트리거합니다 +
. 여기에서는 ChoiceDialog
"ChoiceDialog [일부 항목]를 사용자가 클릭 한 버튼의 값으로 교체"라는 줄에 따라 기본 제공되는 교체 규칙이 있습니다.
True
또는 을 생성하기 위해 규칙 재 작성을 거쳐야하는 조건을 사용하여 규칙을 정의 할 수 있습니다 False
. 예를 들어 새로운 방정식 풀이 방법을 발명했지만 방법의 최종 결과가 양수일 때만 작동한다고 가정 해 보겠습니다. 다음 규칙을 수행 할 수 있습니다.
solve[x + 5 == b_] := (result = b - 5; result /; result > 0)
여기서는 solve[x+5==20]
15로 대체되지만 solve[x + 5 == -20]
적용되는 규칙이 없기 때문에 변경되지 않습니다. 이 규칙이 적용되지 않도록하는 조건은 /;result>0
입니다. Evaluator는 기본적으로 규칙 적용의 잠재적 출력을 살펴보고 계속 진행할지 여부를 결정합니다.
Mathematica의 평가자는 해당 기호에 적용되는 규칙 중 하나로 모든 패턴을 탐욕스럽게 다시 작성합니다. 때로는 더 세밀하게 제어하고 싶을 때가 있습니다. 그런 경우 자신의 규칙을 정의하고 다음과 같이 수동으로 적용 할 수 있습니다.
myrules={area->Pi radius^2,radius->5}
area//.myrules
myrules
결과 변경이 중지 될 때까지에 정의 된 규칙이 적용됩니다 . 이것은 기본 평가자와 매우 유사하지만 이제 여러 규칙 세트를 가지고 선택적으로 적용 할 수 있습니다. 고급 예제 는 일련의 규칙 애플리케이션을 검색하는 Prolog와 유사한 평가자를 만드는 방법을 보여줍니다.
당신이 (의 메이크업에 사용 티카의 기본 평가를 사용해야하는 경우에 현재 매스 매 티카 버전 중 하나 단점은 온다 Integrate
, Solve
등) 및 평가의 변경 기본 순서로합니다. 그것은 가능하지만 복잡합니다 . 그리고 저는 기호 프로그래밍의 일부 미래 구현이 평가 시퀀스를 제어하는 더 우아한 방법을 가질 것이라고 생각합니다.
"기호 프로그래밍"이라는 말을 들었을 때 LISP, Prolog 및 (예) Mathematica가 즉시 떠 오릅니다. 나는 상징적 인 프로그래밍 환경을 프로그램 텍스트를 표현하는 데 사용되는 표현식이 기본 데이터 구조이기도 한 것으로 특징 지을 것입니다. 결과적으로 데이터를 코드로 쉽게 변환하거나 그 반대로 변환 할 수 있기 때문에 추상화를 기반으로 추상화를 구축하는 것이 매우 쉬워집니다.
Mathematica는이 기능을 많이 활용합니다. LISP 및 Prolog (IMHO)보다 훨씬 더 많습니다.
기호 프로그래밍의 예로서 다음과 같은 일련의 이벤트를 고려하십시오. 다음과 같은 CSV 파일이 있습니다.
r,1,2
g,3,4
나는 그 파일을 다음에서 읽었습니다.
Import["somefile.csv"]
--> {{r,1,2},{g,3,4}}
결과 데이터 또는 코드입니까? 둘 다입니다. 파일을 읽은 결과 데이터이지만 해당 데이터를 구성하는 표현식이기도합니다. 그러나 코드가 진행됨에 따라이 표현식은 평가 결과가 단순히 그 자체이기 때문에 비활성입니다.
이제 결과에 변환을 적용합니다.
% /. {c_, x_, y_} :> {c, Disk[{x, y}]}
--> {{r,Disk[{1,2}]},{g,Disk[{3,4}]}}
세부 사항을 고려하지 않고 발생한 모든 것은 Disk[{...}]
각 입력 줄의 마지막 두 숫자를 둘러싼 것입니다. 결과는 여전히 데이터 / 코드이지만 여전히 비활성입니다. 또 다른 변화 :
% /. {"r" -> Red, "g" -> Green}
--> {{Red,Disk[{1,2}]},{Green,Disk[{3,4}]}}
예, 여전히 비활성입니다. 그러나 놀랍게도이 마지막 결과는 Mathematica의 그래픽 용 기본 제공 도메인 별 언어의 유효한 지시문 목록입니다. 마지막으로 한 가지 변화가 일어나기 시작합니다.
% /. x_ :> Graphics[x]
--> Graphics[{{Red,Disk[{1,2}]},{Green,Disk[{3,4}]}}]
사실, 당신은 그 마지막 결과를 보지 못할 것입니다. 통사론 적 설탕의 서사적 디스플레이에서 Mathematica는 빨간색과 녹색 원의 그림을 보여줍니다.
그러나 재미는 여기서 멈추지 않습니다. 그 모든 통 사적 설탕 아래에는 여전히 상징적 인 표현이 있습니다. 다른 변환 규칙을 적용 할 수 있습니다.
% /. Red -> Black
프레스토 악장! 빨간색 원이 검은 색이되었습니다.
상징적 프로그래밍을 특징 짓는 것은 이러한 종류의 "기호 추진"입니다. Mathematica 프로그래밍의 대부분은 이러한 특성을 가지고 있습니다.
기능적 vs. 상징적
심볼릭 프로그래밍과 함수형 프로그래밍의 차이점에 대해서는 자세히 설명하지 않겠지 만 몇 가지 언급 할 것입니다.
One could view symbolic programming as an answer to the question: "What would happen if I tried to model everything using only expression transformations?" Functional programming, by contrast, can been seen as an answer to: "What would happen if I tried to model everything using only functions?" Just like symbolic programming, functional programming makes it easy to quickly build up layers of abstractions. The example I gave here could be easily be reproduced in, say, Haskell using a functional reactive animation approach. Functional programming is all about function composition, higher level functions, combinators -- all the nifty things that you can do with functions.
Mathematica is clearly optimized for symbolic programming. It is possible to write code in functional style, but the functional features in Mathematica are really just a thin veneer over transformations (and a leaky abstraction at that, see the footnote below).
Haskell is clearly optimized for functional programming. It is possible to write code in symbolic style, but I would quibble that the syntactic representation of programs and data are quite distinct, making the experience suboptimal.
Concluding Remarks
In conclusion, I advocate that there is a distinction between functional programming (as epitomized by Haskell) and symbolic programming (as epitomized by Mathematica). I think that if one studies both, then one will learn substantially more than studying just one -- the ultimate test of distinctness.
Leaky Functional Abstraction in Mathematica?
Yup, leaky. Try this, for example:
f[x_] := g[Function[a, x]];
g[fn_] := Module[{h}, h[a_] := fn[a]; h[0]];
f[999]
Duly reported to, and acknowledged by, WRI. The response: avoid the use of Function[var, body]
(Function[body]
is okay).
As others here already mentioned, Mathematica does a lot of term rewriting. Maybe Haskell isn't the best comparison though, but Pure is a nice functional term-rewriting language (that should feel familiar to people with a Haskell background). Maybe reading their Wiki page on term rewriting will clear up a few things for you:
http://code.google.com/p/pure-lang/wiki/Rewriting
Mathematica is using term rewriting heavily. The language provides special syntax for various forms of rewriting, special support for rules and strategies. The paradigm is not that "new" and of course it's not unique, but they're definitely on a bleeding edge of this "symbolic programming" thing, alongside with the other strong players such as Axiom.
As for comparison to Haskell, well, you could do rewriting there, with a bit of help from scrap your boilerplate library, but it's not nearly as easy as in a dynamically typed Mathematica.
Symbolic shouldn't be contrasted with functional, it should be contrasted with numerical programming. Consider as an example MatLab vs Mathematica. Suppose I want the characteristic polynomial of a matrix. If I wanted to do that in Mathematica, I could do get an identity matrix (I) and the matrix (A) itself into Mathematica, then do this:
Det[A-lambda*I]
And I would get the characteristic polynomial (never mind that there's probably a characteristic polynomial function), on the other hand, if I was in MatLab I couldn't do it with base MatLab because base MatLab (never mind that there's probably a characteristic polynomial function) is only good at calculating finite-precision numbers, not things where there are random lambdas (our symbol) in there. What you'd have to do is buy the add-on Symbolab, and then define lambda as its own line of code and then write this out (wherein it would convert your A matrix to a matrix of rational numbers rather than finite precision decimals), and while the performance difference would probably be unnoticeable for a small case like this, it would probably do it much slower than Mathematica in terms of relative speed.
이것이 차이입니다. 기호 언어는 완벽한 정확도로 계산을 수행하는 데 관심이 있으며 (종종 수치가 아닌 유리수를 사용함) 반면에 수치 프로그래밍 언어는 수행해야하는 대부분의 계산에 매우 능숙하며 경향이 있습니다. 그들이 의미하는 수치 연산에서 더 빠르기 위해 (MatLab은 C ++ 등을 제외한 상위 수준의 언어와 관련하여 거의 타의 추종을 불허합니다) 기호 연산에 열악합니다.
참고 URL : https://stackoverflow.com/questions/4430998/mathematica-what-is-symbolic-programming
'Programing' 카테고리의 다른 글
C #에 대한 더 나은 대기 패턴이 있습니까? (0) | 2020.10.12 |
---|---|
Chart.js 선 차트의 레이블 수 제한 (0) | 2020.10.12 |
JavaScript를 사용하여 동적으로 링크에 "href"속성을 추가하려면 어떻게해야합니까? (0) | 2020.10.12 |
단일 파일을 RSYNC하는 방법은 무엇입니까? (0) | 2020.10.12 |
느린 뷰 렌더링의 원인 진단 (0) | 2020.10.12 |