Haskell-拆分数字,然后相乘



基本上,我想要做的是接收一个数字,将其拆分为数字列表,然后将每个值加倍。

但是,我不想使用Integer类型,因为我可能会使用其他一些包含类型变量的函数。我试着做这样的事情:

digs :: (Integral a) => a -> [a] 
digs 0 = []
digs x = digs (x `div` 10) ++ [x `mod` 10]
double :: (Integral a) => [a] -> [a]
double xs = [x*2 | x <- xs]

两个函数都单独工作,但如果我尝试类似";双挖1234";它给了我一个错误。

无法匹配预期的类型"Integer->";实际类型为'[Intere]'的t'

我不知道这个消息是什么意思。

正如评论中所说,您需要编写函数。Haskell将double digs 1234解释为(double digs) 1234。所以haskell认为您正在将函数digs作为参数传递给double。以下是我从您的示例中得到的完整错误消息:

<interactive>:3:1: error:
• Couldn't match expected type ‘Integer -> t’
with actual type ‘[Integer]’
• The function ‘double’ is applied to two arguments,
but its type ‘[Integer] -> [Integer]’ has only one
In the expression: double digs 1234
In an equation for ‘it’: it = double digs 1234
• Relevant bindings include it :: t (bound at <interactive>:3:1)
<interactive>:3:8: error:
• Couldn't match expected type ‘[Integer]’
with actual type ‘Integer -> [Integer]’
• Probable cause: ‘digs’ is applied to too few arguments
In the first argument of ‘double’, namely ‘digs’
In the expression: double digs 1234
In an equation for ‘it’: it = double digs 1234

在第一个错误消息中注意:;函数double应用于两个参数,但其类型只有一个"Haskell将其解读为先传递digs到double,然后传递1234。

因此,您需要确保1234首先传递给digs,然后将结果传递给double。我认为最适合初学者的方法是使用parens:

*Main> double (digs 1234)
[2,4,6,8]

Haskell的函数调用风格与大多数语言非常不同,因此需要一些时间才能适应

最新更新