SEDOLs: Difference between revisions

Content added Content deleted
(Add Rust implementation)
(→‎{{header|Haskell}}: Added test case and output for ill-formed sedol string.)
Line 1,629: Line 1,629:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.Char (isDigit, isAsciiUpper, ord)
<lang haskell>import Data.Char (isAsciiUpper, isDigit, ord)

-------------------------- SEDOLS ------------------------


checkSum :: String -> String
checkSum :: String -> String
checkSum =
checkSum x =
case traverse sedolValue x of
show .
Right xs -> checkSumFromSedolValues xs
(`rem` 10) .
Left annotated -> annotated
(-) 10 . (`rem` 10) . sum . zipWith (*) [1, 3, 1, 7, 3, 9] . fmap charValue

checkSumFromSedolValues :: [Int] -> String
checkSumFromSedolValues xs =
show $
rem
( 10
- rem
( sum $
zipWith
(*)
[1, 3, 1, 7, 3, 9]
xs
)
10
)
10

sedolValue :: Char -> Either String Int
sedolValue c
| c `elem` "AEIOU" = Left " ← Unexpected vowel."
| isDigit c = Right (ord c - ord '0')
| isAsciiUpper c = Right (ord c - ord 'A' + 10)


charValue :: Char -> Int
charValue c
| c `elem` "AEIOU" = error "No vowels."
| isDigit c = ord c - ord '0'
| isAsciiUpper c = ord c - ord 'A' + 10


-- TEST ----------------------------------------------------------------------
--------------------------- TEST -------------------------
main :: IO ()
main :: IO ()
main =
main =
mapM_
mapM_
(putStrLn . ((++) <*> checkSum))
(putStrLn . ((<>) <*> checkSum))
[ "710889"
[ "710889",
, "B0YBKJ"
"B0YBKJ",
, "406566"
"406566",
, "B0YBLH"
"B0YBLH",
, "228276"
"228276",
, "B0YBKL"
"B0YBKL",
, "557910"
"557910",
, "B0YBKR"
"B0YBKR",
, "585284"
"585284",
, "B0YBKT"
"B0YBKT",
"BOYBKT", -- Ill formed test case - illegal vowel.
, "B00030"
"B00030"
]</lang>
]</lang>
{{Out}}
{{Out}}
Line 1,671: Line 1,691:
5852842
5852842
B0YBKT7
B0YBKT7
BOYBKT ← Unexpected vowel.
B000300</pre>
B000300</pre>