【发布时间】:2020-05-24 12:46:14
【问题描述】:
Libs.hs:
--TAKE INPUT OF USER CARD DETAILS AND SEPERATE EACH DIGIT AND INTO A LIST
getCard :: Integer -> [Integer]
getCard x
| x <= 0 = []
| otherwise = lst_numb : getCard pre_numb
where
(pre_numb, lst_numb) = x `divMod` 10
--TAKE SEPERATED DIGITS LIST AND REVERSE
cardNumber :: Integer -> [Integer]
cardNumber = reverse . getCard
--DOUBLE EVERY OTHER NUMBER STARTING FROM THE RIGHT (TO THE LEFT OF CHECK NUMBER)
doubleNumber :: [Integer] -> [Integer]
doubleNumber [] = []
--doubleNumber (x:y:xs) = 2*x : y : doubleNumber xs //This is the partially working function for Q2
doubleNumber (x:y:xs)
| validFormat (x:y:xs) == True = 2*x : y : doubleNumber xs
|otherwise = []
--CHECKS ISSUER ID IS VALID & CARD NUMBER IS 16 DIGITS LONG
validFormat :: [Integer] -> Bool
validFormat x
| x == [] = False
| (head x == 3 || head x == 4 || head x == 5 || head x == 6) && length x == 16 = True
| otherwise = False
--ADDITION OF ALL DIGITS INSIDE THE LIST
addNumbers :: [Integer] -> Integer
addNumbers xs = sum xs
--SUBTRACT NINE FROM DOUBBLE DIGIT NUMBERS
subDoubles :: [Integer] -> [Integer]
subDoubles [] = []
subDoubles (x:xs)
| x > 9 = x - 9 : subDoubles xs
| otherwise = x : subDoubles xs
--COMBINED FUNCTION TO VALIDATE A CREDIT CARD NUMBER
validateCard :: Integer -> Bool
validateCard x = compute x `mod` 10 == 0
where
compute :: Integer -> Integer
compute = addNumbers . subDoubles . doubleNumber . cardNumber
--DISPLAY USER MSG IF CARD IS VALID OR NOT
isValid card
| card == True = "This is a valid credit card!"
| otherwise = "This card is invalid"
Main.hs:
main :: IO ()
main = do
putStrLn "Please enter a credit card number:"
input <- getLine
let card = read input :: Integer
isValid . validateCard card
我有一个 Haskell 项目,可以根据用户输入验证信用卡号(如上面在 Libs.hs 中):
我可以在 ghci 中使用带有数字的 validateCard 函数,它会产生真或假。我希望用户在 Main.hs 文件中输入一个信用卡号,并获得一个字符串来宣传他们的输入是有效还是无效,但是,我不知道我是否正确调用了 main.hs 中的 validateCard 函数。有人可以解释一下我的方法哪里出了问题吗? 已经有一段时间了,所以任何建议或建议将不胜感激。提前谢谢!
编辑: 我上传的代码是我正在尝试的代码,但这是我尝试的初始方式,它无法正常工作
【问题讨论】:
-
使用
getLine获取用户输入,然后在其上运行您的函数。您需要先将其从字符串转换为整数文件。 -
你的最后一行
isValid.card <- validateCard在语法上不正确 Haskell。将<-视为近似等于:=。 -
@RobinZigmond 我为我的 main.hs 上传了错误的代码,这是我最初尝试的方式,但仍然遇到问题
-
@PaulJohnson 抱歉,这不是我要上传的内容,此编辑后的帖子在匹配预期类型时会出错
-
投票结束,帖子缺乏焦点。
标签: haskell user-input where-clause main