简体   繁体   English

Haskell中的拆分功能是什么?

[英]What does split in Haskell do?

I'm new to Haskell and I came into the code below and don't actually understand what it does. 我是Haskell新手,我进入了下面的代码,但实际上并不了解它的作用。 I know that the toDigits function is declared to take an Integer and return an array of Integer s. 我知道toDigits函数声明为采取一个Integer ,并返回数组Integer秒。 If the argument n equals 0 or less, we return an empty array, otherwise...? 如果参数n等于或小于0,则返回一个空数组,否则...? That's the mystery! 那是个谜!

toDigits :: Integer -> [Integer]
toDigits n
  | n < 1     = []
  | otherwise = reverse $ split [] n
    where split _   0 = []
          split acc m = lastDigit m : split acc (dropLastDigit m)

Could you please explain to me? 你能给我解释一下吗?

reverse $ split [] n

Is the same as 是相同的

reverse (split [] n)

It reverses the return value of split [] n and returns the result. 它反转split [] n的返回值并返回结果。

Split is defined in the next line. 拆分在下一行中定义。

It takes a list (an accumulator) and an Integer and does this: 它需要一个列表(一个累加器)和一个整数,并执行以下操作:

Note that I assume that split is defined as follows (current implementation does not use acc). 请注意,我假定split定义如下(当前实现不使用acc)。 I also assume lastDigit and dropLastDigit do as their names would suggest: 我还假设lastDigitdropLastDigit会按照它们的名称进行提示:

split acc 0 = acc
split acc m = split (lastDigit m : acc) (dropLastDigit m)

Now, split returns acc if m is zero, otherwise it recursively prepends last digit of m to acc and pass it as the first argument to split , and removes the last digit from m and pass it as the second argument to split . 现在,如果m为零, split将返回acc ,否则它将m的最后一位递归加到acc并将其作为split的第一个参数传递,并从m中删除最后一位并将其作为split的第二个参数传递。 In other words, this function eventually splits a number to its digits and returns the result as a list of Integers. 换句话说,该函数最终将一个数字除以其数字,然后将结果作为整数列表返回。 Having this said calling split [] 1234 would return [1, 2, 3, 4] . 这样说,调用split [] 1234将返回[1, 2, 3, 4] You probably don't need to reverse the result of calling split. 您可能不需要撤销调用split的结果。

Here, it takes a number and builds a list of its digits, one by one. 在这里,它采用一个数字并逐一建立其数字列表。 At each moment it first checks whether the number argument is zero (then the returned value is an empty list), and, if not, a) takes its last digit; 在每个时刻,它首先检查number参数是否为零(然后返回的值是一个空列表),如果不是,则取其最后一位; b) prepends the digit to the result of a recursive call to itself, now with number with the last digit dropped. b)将数字添加到对其自身进行递归调用的结果之前,现在将数字删除最后一位。 The acc argument is never actually used, since the recursion was finally settled to be modulo cons. acc参数从未实际使用过,因为递归最终被确定为模态缺点。

Note that list is finally built in least-endian order: the first element to the list is the least significant digit of the number. 请注意,列表最终以最低字节序排列:列表的第一个元素是数字的最低有效位。

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

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