UPC: Difference between revisions

Content deleted Content added
Mihailp (talk | contribs)
add PicoLisp
Chunes (talk | contribs)
Add Factor
Line 47:
 
Finally, the last digit is a checksum digit which may be used to help detect errors. Multiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add products, and the sum (mod 10) must be 0 (must have a zero as its last digit) if the number has been read correctly.
 
=={{header|Factor}}==
{{works with|Factor|0.99 2019-10-06}}
<lang factor>USING: combinators combinators.short-circuit formatting grouping
kernel locals math math.vectors sequences sequences.repeating
unicode ;
 
CONSTANT: numbers {
" ## #"
" ## #"
" # ##"
" #### #"
" # ##"
" ## #"
" # ####"
" ### ##"
" ## ###"
" # ##"
}
 
: upc>dec ( str -- seq )
[ blank? ] trim 3 tail 3 head* 42 cut 5 tail
[ 35 = 32 35 ? ] map append 7 group [ numbers index ] map ;
 
: valid-digits? ( seq -- ? ) [ f = ] none? ;
 
: valid-checksum? ( seq -- ? )
{ 3 1 } 12 cycle v* sum 10 mod zero? ;
 
: valid-upc? ( seq -- ? )
{ [ valid-digits? ] [ valid-checksum? ] } 1&& ;
 
:: process-upc ( upc -- obj upside-down? )
upc upc>dec :> d
{
{ [ d valid-upc? ] [ d f ] }
{ [ upc reverse upc>dec dup valid-upc? ] [ t ] }
{ [ drop d valid-digits? ] [ "Invalid checksum" f ] }
[ "Invalid digit(s)" f ]
} cond ;
 
{
" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # "
" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # "
" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # "
" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # "
" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # "
" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # "
" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # "
" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # "
" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # "
" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # "
}
[ process-upc "(upside down)" "" ? "%u %s\n" printf ] each</lang>
{{out}}
<pre>
{ 9 2 4 7 7 3 2 7 1 0 1 9 }
{ 4 0 3 9 4 4 4 4 1 0 5 0 }
{ 8 3 4 9 9 9 6 7 6 7 0 6 } (upside down)
{ 9 3 9 8 2 5 1 5 8 8 1 1 } (upside down)
"Invalid digit(s)"
{ 3 1 6 3 1 3 7 1 8 7 1 7 } (upside down)
{ 2 1 4 5 7 5 8 7 5 6 0 8 }
{ 8 1 8 7 7 8 8 4 1 8 1 3 } (upside down)
{ 7 0 6 4 6 6 7 4 3 0 3 0 }
{ 6 5 3 4 8 3 5 4 0 4 3 5 }
</pre>
 
=={{header|Go}}==