ممبس
برامج عينات

إن التنفيذ المباشر للشيفرة المصدرية على منصات الحوسبة التاريخية في عهد الأقراص الدقيقة، والرامات صغيرة ووصلات 300 بود التسلسلية قد أدت إلى أسلوب تشفير تاريخي كان مكثفا ومصاحبا للخبراء، حتى أن أساليب التشفير المعاصرة لممبس تنتج حاليا تشفيرا أكثر قابلية للقراءة.
أولا، كمثال لشيفرة M من عام 2010، فإن حلا لتدريب قياسي قائم على حساب المتوالية الأطول المتحققة عند حساب المتوالية الأطول حدس كولاتز لمجموعة من المكملين. وهذا المثال مكتوب بلغة GT.M ويستغل ويجسد العديد من مميزات ممبس
threeen1f
        ; Find the maximum number of steps for the 3n+1 problem for all integers through two input integers.
        ; See http://docs.google.com/View?id=dd5f3337_24gcvprmcw
        ; Assumes input format is 3 integers separated by a space with the first integer smaller than the second.
        ; The third integer is the number of parallel computation streams.  If it is less than twice the
        ; number of CPUs or cores, the parameter is modified to that value.  An optional fourth integer is the
        ; sizes of blocks of integers on which spawned child processes operate.  If it is not specified, the
        ; block size is approximately the range divided by the number of parallel streams.  If the block size is
        ; larger than the range divided by the number of execution streams, it is reduced to that value.
        ; No input error checking is done.

        ; Although the problem can be solved by using strictly integer subscripts and values, this program is
        ; written to show that the GT.M key-value store can use arbitrary strings for both keys and values -
        ; each subscript and value is spelled out using the strings in the program source line labelled "digits".
        ; Furthermore, the strings are in a number of international languages when GT.M is run in UTF-8 mode.

        ; K.S. Bhaskar 2010612

        ; No claim of copyright is made with respect to this program.

        ; Variables do not have to be declared before use, but are New'd in subprograms to ensure that they
        ; do not conflict with names in the caller.

        ; The program reads the program source at the label digits to get strings (separated by ;) for each language used.
digits ;zero;eins;deux;tres;quattro;пять;ستة;सात;捌;ஒன்பது
        Do digitsinit                           ; Initialize data for conversion between integers and strings

        ; Get number of CPUs from /proc/cpuinfo and calculate minimum number of execution streams
        Open "cpus":(SHELL="/bin/sh":COMMAND="grep -i ^processor /proc/cpuinfo|wc -l":READONLY)::"PIPE"
        Use "cpus" Read streams Use $PRINCIPAL
        Close "cpus"
        Set streams=2*streams                   ; At least two execution streams per CPU

        ; At the top level, the program reads and processes input lines, one at a time.  Each line specifies
        ; one problem to solve.  Since the program is designed to resume after a crash and reuse partial
        ; results computed before the crash, data in the database at the beginning is assumed to be partial
        ; results from the previous run.  After computing and writing results for a line, the database is
        ; cleared for next line of input or next run of the program.

        ; Loop for ever, read a line (quit on end of file), process that line
        For  Read input Quit:$ZEOF!'$Length(input)  Do      ; input has entire input line
      .
      . Set i=$Piece(input," ",1)                         ; i - first number on line is starting integer for the problem
      . Set j=$Piece(input," ",2)                         ; j - second number on line is ending integer for the problem
      . Write $FNumber(i,",",0)," ",$FNumber(j,",",0)     ; print starting and ending integers, formatting with commas
      .
      . Set k=$Piece(input," ",3)                         ; k - third number on input line is number of parallel streams
      . If streams>k Do                                   ; print number of execution streams, optionally corrected
      ..  Write " (",$FNumber(k,",",0)
      ..  Set k=streams
      ..  Write "->",$FNumber(k,",",0),")"
      . Else  Write " ",$FNumber(k,",",0)
      .
      . Set blk=+$Piece(input," ",4)                          ; blk - size of blocks of integers is optional fourth piece
      . Set tmp=(j-i+k)\k                                     ; default / maximum block size
      . If blk&(blk'>tmp) Write " ",$FNumber(blk,",",0)       ; print block size, optionally corrected
      . Else  Do
      ..  Write " (",$FNumber(blk,",",0)
      ..  Set blk=tmp
      ..  Write "->",$FNumber(blk,",",0),")"
      .
      . ; Define blocks of integers for child processes to work on
      . Kill ^limits
      . Set tmp=i-1
      . For count=1:1 Quit:tmp=j  Do
      ..  Set ^limits(count)=$increment(tmp,blk)
      ..  Set:tmp>j (tmp,^limits(count))=j
      .
      . ; Launch jobs.  Grab lock l1, atomically increment counter, compute and launch one job for each block of numbers.
      . ; Each child job locks l2(pid), decrements the counter and tries to grab lock l1(pid).
      . ; When counter is zero, all jobs have started.  Parent releases lock l1 and tries to grab lock l2.
      . ; When all children have released their l2(pid) locks, they're done and parent can gather & report results.
      . Set ^count=0                                  ; Clear ^count - may have residual value if restarting from crash
      . Lock +l1                                      ; Set lock for process synchronization
      . For s=1:1:k Do
      ..  Set c=$Increment(^count)                    ; Atomic increment of counter in database for process synchronization
      ..  Set def=$ZTRNLNM("gtm_tmp") Set:'$Length(def) def=$ZTRNLNM("PWD")     ; Working directory for Jobbed process
      ..  Set err=$Text(+0)_"_"_$Job_"_"_s_".mje"                               ; STDERR for Jobbed process
      ..  Set out=$Extract(err,1,$Length(err)-1)_"o"                            ; STDOUT for Jobbed process
      ..  Set cmd="doblk(i):(ERROR="""_err_""":OUTPUT="""_out_""":DEFAULT="""_def_""")"     ; Command to Job
      ..  Job @cmd                             ; Job child process for next block of numbers
      . For  Quit:'^count  Hang 0.1            ; Wait for processes to start (^count goes to 0 when they do)
      . Lock -l1                               ; Release lock so processes can run
      . Set startat=$HOROLOG                   ; Get starting time
      . Lock +l2                               ; Wait for processes to finish
      .
      . ; When parent gets lock l2, child processes have completed and parent gathers and reports results.
      . set endat=$HOROLOG                     ; Get ending time - time between startat and endat is the elapsed time
      . ; Calculate duration
      . Set duration=(86400*($Piece(endat,",",1)-$Piece(startat,",",1)))+$Piece(endat,",",2)-$Piece(startat,",",2)
      . Write " ",$FNumber(^result,",",0)     ; Show largest number of steps for the range i through j
      . Write " ",$FNumber(^highest,",",0)    ; Show the highest number reached during the computation
      . Write " ",$FNumber(duration,",",0)    ; Show the elapsed time 
      . Write " ",$FNumber(^updates,",",0)    ; Show number of updates
      . Write " ",$FNumber(^reads,",",0)      ; Show number of reads
      . ; If duratation is greater than 0 seconds, display update and read rates
      . Write:duration " ",$FNumber(^updates/duration,",",0)," ",$FNumber(^reads/duration,",",0)
      . Write !
      . Lock -l2                               ; Release lock for next run
      . Do dbinit                              ; Initialize database for next run
        Quit

dbinit ; Entryref dbinit clears database between lines
        Kill ^count,^highest,^reads,^result,^step,^updates
        Quit

digitsinit ; Initialize arrays to convert between strings and integers
        New m,x
        Set x=$Text(digits)
        For m=0:1:9 Set di($Piece(x,";",m+2))=m,ds(m)=$Piece(x,";",m+2)
        Quit

inttostr(n) ; Convert an integer to a string
        New m,s
        Set s=ds($Extract(n,1))
        For m=2:1:$Length(n) Set s=s_" "_ds($Extract(n,m))
        Quit s
        ;
strtoint(s) ; Convert a string to an integer
        New m,n
        Set n=di($Piece(s," ",1))
        For m=2:1:$Length(s," ") Set n=10*n+di($Piece(s," ",m))
        Quit n

; This is where Jobbed processes start
doblk(allfirst)
        Set (reads,updates,highest)=0           ; Start with zero reads, writes and highest number
        Do digitsinit                           ; Initialize data for conversion between integers and strings
        Lock +l2($JOB)                          ; Get lock l2 that parent will wait on till this Jobbed processes is done
        If $Increment(^count,-1)                ; Decrement ^count to say this process is alive
        Lock +l1($JOB)                          ; This process will get lock l1($JOB) only parent has released lock on l1
        ;
        ; Process the next block in ^limits that needs processing; quit when done
        For  Quit:'$Data(^limits($increment(tmp)))  Do:1=$increment(^limits(tmp,1)) dostep($select($data(^limits(tmp-1)):^limits(tmp-1)+1,1:allfirst),^limits(tmp))
        ;
        TStart ()                               ; Update global statistics inside a transaction
        ; The following line unconditionally adds the number of reads & write performed by this process to the
        ; number of reads & writes performed by all processes, and sets the highest for all processes if the
        ; highest calculated by this process is greater than that calculated so far for all processes
        Set:$Increment(^reads,reads)&$Increment(^updates,updates)&(highest>$Get(^highest)) ^highest=highest
        TCommit
        Lock -l1($JOB),-l2($JOB)                ; Release locks to tell parent this parent is done
        Quit                                    ; Jobbed processes terminate here

dostep(first,last) ; Calculate the maximum number of steps from first through last
        New current,currpath,i,n
        For current=first:1:last Do
      . Set n=current                          ; Start n at current
      . Kill currpath                          ; Currpath holds path to 1 for current
      . ; Go till we reach 1 or a number with a known number of steps
      . For i=0:1 Quit:$Increment(reads)&($Data(^step($$inttostr(n)))!(1=n))  Do
      ..  Set currpath(i)=n                     ; log n as current number in sequence
      ..  Set n=$Select('(n#2):n/2,1:3*n+1)     ; compute the next number
      ..  Set:n>highest highest=n             ; see if we have a new highest number reached              
      . Do:0<i                                 ; if 0=i we already have an answer for n, nothing to do here
      ..  If 1<n Set i=i+$$strtoint(^step($$inttostr(n)))
      ..  TStart ()                             ; Atomically set maximum
      ..  Set:i>$Get(^result) ^result=i
      ..  TCommit
      ..  Set n="" For  Set n=$Order(currpath(n)) Quit:""=n  Set:$Increment(updates) ^step($$inttostr(currpath(n)))=$$inttostr(i-n)
        Quit
وفيما يلي، فإن هناك مثال لأسلوب التشفير M «التقليدي»، وهو نظام التشفير المصدري VistA منذ أواخر السبعينيات (آخر تعديل له في 1992)، وقد كتبه في صورته الأصلية جورج تيمسون في الوقت الذي كانت فيه المعايرة اللغوية غير ذات مميزات متطورة مثل التأطير المتغير. ومن المعترف به على وجه العموم أن هذا التشفير ليس قابلا للقراءة بصورة قوية بالنسبة للعديد من مبرمجي اليوم. ومع ذلك فإنه يجب أن نذكر أن هذا التشفير مقبول للخبراء، (على سبيل المثال بالنسبة لمبرمجي VistA المتكيفين معه فإنه يكون مقروئا ومبنيا بشكل مناسب)- إن هذا التشفير مثال للتشفير الذي كان يستخدم بفاعلية لمدة سنوات عديدة. إن هذه الثقافة والأسلوب لتشفير تطبيق طويل الأمد لا يمكن ولا يجب أن تتغير بين ليلة وضحاها، وعندما يستمر التشفير في العمل فإن مثل هذه الثقافات تركز على إضافة وظيفية جديدة بدر من تحديث التشفير ببساطة لأسباب واقعية.
وبسبب الطبيعية المقتضبة لتشفير ممبس المختصر تماما، فإن حجم التشفير المشابه في لغات البرمجة الأخرى التي تقدم نفس الوظيفية يمكن أن تكون أكبر بصورة كبيرة.
%DTC
%DTC ; SF/XAK - DATE/TIME OPERATIONS ;1/16/92 11:36 AM
     ;;19.0;VA FileMan;;Jul 14, 1992
     D    I 'X1!'X2 S X="" Q
     S X=X1 D H S X1=%H,X=X2,X2=%Y+1 D H S X=X1-%H,%Y=%Y+1&X2
     K %H,X1,X2 Q
     ;
C S X=X1 Q:'X D H S %H=%H+X2 D YMD S:$P(X1,".",2) X=X_"."_$P(X1,".",2) K X1,X2 Q
S S %=%#60/100+(%#3600\60)/100+(%\3600)/100 Q
     ;
H I X<1410000 S %H=0,%Y=-1 Q
     S %Y=$E(X,1,3),%M=$E(X,4,5),%D=$E(X,6,7)
     S %T=$E(X_0,9,10)*60+$E(X_"000",11,12)*60+$E(X_"00000",13,14)
TOH S %H=%M>2&'(%Y#4)+$P("^31^59^90^120^151^181^212^243^273^304^334","^",%M)+%D
     S %='%M!'%D,%Y=%Y-141,%H=%H+(%Y*365)+(%Y\4)-(%Y>59)+%,%Y=$S(%:-1,1:%H+4#7)
     K %M,%D,% Q
     ;
DOW D H S Y=%Y K %H,%Y Q
DW D H S Y=%Y,X=$P("SUN^MON^TUES^WEDNES^THURS^FRI^SATUR","^",Y+1)_"DAY"
     S:Y<0 X="" Q
7 S %=%H>21608+%H-.1,%Y=%\365.25+141,%=%#365.25\1
     S %D=%+306#(%Y#4=0+365)#153#61#31+1,%M=%-%D\29+1
     S X=%Y_"00"+%M_"00"+%D Q
     ;
YX D YMD S Y=X_% G DD^%DT
YMD D 7 S %=$P(%H,",",2) D S K %D,%M,%Y Q
T F %=1:1 S Y=$E(X,%) Q:"+-"[Y G 1^%DT:$E("TODAY",%)'=Y
     S X=$E(X,%+1,99) G PM:Y="" I +X'=X D DMW S X=%
     G:'X 1^%DT
PM S @("%H=$H"_Y_X) D TT G 1^%DT:%I(3)'?3N,D^%DT
N F %=2:1 S Y=$E(X,%) Q:"+-"[Y G 1^%DT:$E("NOW",%)'=Y
     I Y="" S %H=$H G RT
     S X=$E(X,%+1,99)
     I X?1.N1"H" S X=X*3600,%H=$H,@("X=$P(%H,"","",2)"_Y_X),%=$S(X<0:-1,1:0)+(X\86400),X=X#86400,%H=$P(%H,",")+%_","_X G RT
     D DMW G 1^%DT:'% S @("%H=$H"_Y_%),%H=%H_","_$P($H,",",2)
RT D TT S %=$P(%H,",",2) D S S %=X_% I %DT'["S" S %=+$E(%,1,12)
     Q:'$D(%(0))  S Y=% G E^%DT
PF S %H=$H D YMD S %(9)=X,X=%DT["F"*2-1 I @("%I(1)*100+%I(2)"_$E("> <",X+2)_"$E(%(9),4,7)") S %I(3)=%I(3)+X
     Q
TT D 7 S %I(1)=%M,%I(2)=%D,%I(3)=%Y K %M,%D,%Y Q
NOW S %H=$H,%H=$S($P(%H,",",2):%H,1:%H-1)
     D TT S %=$P(%H,",",2) D S S %=X_$S(%:%,1:.24) Q
DMW S %=$S(X?1.N1"D":+X,X?1.N1"W":X*7,X?1.N1"M":X*30,+X=X:X,1:0)
     Q
COMMA ;
     S %D=X<0 S:%D X=-X S %=$S($D(X2):+X2,1:2),X=$J(X,1,%),%=$L(X)-3-$E(23456789,%),%L=$S($D(X3):X3,1:12)
     F %=%:-3 Q:$E(X,%)=""  S X=$E(X,1,%)_","_$E(X,%+1,99)
     S:$D(X2) X=$E("$",X2["$")_X S X=$J($E("(",%D)_X_$E(")",%D+1),%L) K %,%D,%L
     Q
HELP S DDH=$S($D(DDH):DDH,1:0),A1="Examples of Valid Dates:" D %
     S A1="  JAN 20 1957 or 20 JAN 57 or 1/20/57"_$S(%DT'["N":" or 012057",1:"") D %
     S A1="  T   (for TODAY),  T+1 (for TOMORROW),  T+2,  T+7,  etc." D %
     S A1="  T-1 (for YESTERDAY),  T-3W (for 3 WEEKS AGO), etc." D %
     S A1="If the year is omitted, the computer "_$S(%DT["P":"assumes a date in the PAST.",1:"uses the CURRENT YEAR.") D %
     I %DT'["X" S A1="You may omit the precise day, as:  JAN, 1957" D %
     I %DT'["T",%DT'["R" G 0
     S A1="If the date is omitted, the current date is assumed." D %
     S A1="Follow the date with a time, such as JAN 20@10, T@10AM, 10:30, etc." D %
     S A1="You may enter a time, such as NOON, MIDNIGHT or NOW." D %
     I %DT["S" S A1="Seconds may be entered as 10:30:30 or 103030AM." D %
     I %DT["R" S A1="Time is REQUIRED in this response." D %
0 Q:'$D(%DT(0))
     S A1=" " D % S A1="Enter a date which is "_$S(%DT(0)["-":"less",1:"greater")_" than or equal to " D %
     S Y=$S(%DT(0)["-":$P(%DT(0),"-",2),1:%DT(0)) D DD^%DT:Y'["NOW"
     I '$D(DDS) W Y,"." K A1 Q
     S DDH(DDH,"T")=DDH(DDH,"T")_Y_"." K A1 Q
     ;
% I '$D(DDS) W !," ",A1 Q
     S DDH=DDH+1,DDH(DDH,"T")="     "_A1 Q
وفيما يلي تطبيقا ثانيا والذي يجسد إمكانات الإيجاز في ممبس.
ST ; ROT13 ; Gunter Rensch ; 2000-01-03 ; Encrypt/Decrypt ROT13
        Q ; no direct execution
        ;
        ; call from your program with
        ;       S A="String"
        ;       S A=$$ROT^ROT13(.A)
        ;
ROT(R) ;
        S S1="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        S S2="NOPQRSTUVWXYZABCDEFGHIJKLM"
        S s1="abcdefghijklmnopqrstuvwxyz"
        S s2="nopqrstuvwxyzabcdefghijklm"
        S R=$TR(R,S1_s1,S2_s2)
        Q R
A second implementation is below, which illustrates the possibilities of concision in MUMPS.
s A="String" F i=1:1:$L(A) W $c($S($A($E(A,i))<91:$A($E(A,i))-52#26+65,1:$A($E(A,i))-84#26+97))
أخيرا فإن أحد أقصر البرامج التي كتبت من قبل بلغة رفيعة المستوى، مظهرا الإيجاز المطلق الذي تكون ممبس قادرة عليه
s x="x x" x x
ويقوم نفس اللوغاريتم باستخدام متغير موسع وأسماء أوامر
Set X="Xecute X" Xecute X
ويقوم هذا البرنامج بوضع قيمة "xx" للاسم المتغير x، ثم يبدأ تنفيذا مطلقا لـ x يمكن أن يسفر عن تدفق مفرط في التكويم. وعند مجرد 13 حرف، بما فيها الفراغات وعلامة نهاية السطر (لأن معايرة ممبس تحدد السعة التخزينية بالحروف وليس بالبايت)، باستخدام حرفين، يظهر المتغير الأول أنه من الممكن أيضا كتابة تشفير موجز في M.