Skip to content

Instantly share code, notes, and snippets.

@mndrix
Created February 21, 2009 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mndrix/67799 to your computer and use it in GitHub Desktop.
Save mndrix/67799 to your computer and use it in GitHub Desktop.
UPC validation in Haskell
module UPC (is_upc) where
import Data.Char (digitToInt)
-- Is this string a valid Universal Product Code?
is_upc :: String -> Bool
is_upc u = ( length u == 12 ) && ( upc_checksum u `mod` 10 == 0 )
-- Calculate the UPC checksum using the algorithm from http://xrl.us/omxh8
upc_checksum :: String -> Int
upc_checksum upc = sum evens + 3*sum odds
where digits = zip [1..12] $ map digitToInt upc
odds = [ x | (n,x) <- digits, odd n ]
evens = [ x | (n,x) <- digits, not ( odd n ) ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment