简体   繁体   English

尝试检查在haskell中划分原始数字的数字

[英]Trying to check digits that divide original number in haskell

Haskell Code Problem Description: Code is supposed to return how many digits in the number divide the number as a whole. Haskell 代码问题描述:代码应该返回数字中有多少位数字作为一个整体。 For example, 12 has two digits [1, 2], both of which divide 2 (12%2 and 12%1 are both 0) so 2 is returned as there are two digits that divide the number.例如,12 有两个数字 [1, 2],这两个数字都可以整除 2(12%2 和 12%1 都是 0),因此返回 2,因为有两个数字可以整除该数字。 For 102, 2 is returned as 1 and 2 both divide 102, division by 0 is undefined.对于 102,2 返回为 1 和 2 都除以 102,除以 0 是未定义的。

However, with this code I get errors with numbers containing 0s in the middle of the number (eg 1001020) I get "Program Error: Prelude.read: no parse"但是,使用此代码时,我会收到在数字中间包含 0 的数字错误(例如 1001020),我收到“程序错误:Prelude.read:no parse”

Any help will be greatly appreciated.任何帮助将不胜感激。 Many thanks.非常感谢。

import Control.Monad
import Data.Array
import Data.Bits
import Data.Char
import Data.List
import Data.Set
import Debug.Trace
import System.Environment
import System.IO
import System.IO.Unsafe

findDigits :: Int -> Int
findDigits n = digits n n 0 (lengths n)
    where
        digits n on count endCheck
            | endCheck == 0 = count
            | header n == 0 = digits (tailer n) on count (endCheck-1)
            | on `mod` header n == 0 = digits (tailer n) on (count+1) (endCheck-1)
            | otherwise = digits (tailer n) on count (endCheck-1)

header :: Int -> Int
header x = digitToInt . head . show $ x

tailer :: Int -> Int
tailer x = read . tail . show $ x

lengths :: Int -> Int
lengths x = length . show $ x

I think you are trying to do too much in a function.我认为你试图在一个函数中做太多事情。 Uually it is better to work with small functions that each solve a simple task, and then combine these in functions that are small as well, and perform a (slightly) more sophisticated task.通常最好使用每个都解决一个简单任务的小函数,然后将它们组合到同样小的函数中,并执行(稍微)更复杂的任务。

For example we can make a function digits :: Int -> [Int] that returns a list of digits:例如,我们可以创建一个函数digits :: Int -> [Int]来返回一个数字列表:

digits :: Int -> [Int]
digits x | x >= 10 = r : digits q
         | otherwise = [x]
    where (q,r) = quotRem x 10

For example:例如:

Prelude> digits 102
[2,0,1]

We can then filter these digits to check that the digits are not zero (since then it is not dividable), and that the number is dividable by that digit:然后我们可以过滤这些数字以检查这些数字是否不为零(因为它不可整除),以及该数字是否可以被该数字整除:

dividableDigits :: Int -> [Int]
dividableDigits n = filter (\x -> x /= 0 && mod n x == 0) (digits n)

Now it is a matter of counting the numbers that match.现在是计算匹配的数字的问题。 I leave that as an exercise.我把它留作练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM