简体   繁体   English

在自然数上使用加法函数,给出自然数乘法的递归定义吗?

[英]Using the addition function over the natural numbers, give a recursive definition of multiplication of natural numbers?

I have the following exercise but am not sure on how I should begin. 我进行以下练习,但是不确定如何开始。 The wording doesn't make sense to me: 这种措辞对我来说没有意义:

Using the addition function over the natural numbers, give a recursive definition of multiplication of natural numbers. 在自然数上使用加法函数,给出自然数乘法的递归定义。

You can think of 3 * 5 as 5 + 5 + 5 , ie adding 5 for 3 times. 您可以将3 * 5视为5 + 5 + 5 ,即将35 If you want to do it recursively, then you can think of it like this: the result of a * b is equal to adding b to the result of (a-1) * b . 如果要递归执行,则可以这样考虑: a * b的结果等于将b添加到(a-1) * b的结果中。 From here to a Haskell recursive function, the step is small :) 从这里到Haskell递归函数,步骤很小:)

mul(n,1) = n
mul(n,m) = mul(n,m-1) + n

something like this 这样的事情

One definition would be: 一种定义是:

mul m n = sum $ replicate m n

Here replicate ab creates a list containing a copies of b, eg replicate 3 5 = [5,5,5]. 在这里, replicate ab创建一个包含b的副本的列表,例如,复制3 5 = [5,5,5]。 sum gives the sum of a list, eg sum [5,5,5] is 15. Bingo! sum给出列表的总和,例如sum [5,5,5]为15。

Of course using the built-in functions would be cheating, so how could you write these functions yourself? 当然,使用内置函数会带来欺骗,那么您如何自己编写这些函数呢? I'll give you some hints: 我会给你一些提示:

replicate' 0 x = [] 
replicate' n x = x : ??? 

sum' [] = 0
sum' (x:xs) = ???

Generally it is a good homework strategy to look for predefined functions (eg using Hoogle) in order to solve the general problem, and to substitute that functions one by one. 通常,寻找预定义的功能(例如使用Hoogle)以解决一般问题,并逐个替换该功能是一种不错的作业策略。 This helps to divide the problems in manageable steps, and gives you a free introduction of the Haskell API. 这有助于将问题划分为可管理的步骤,并为您免费介绍Haskell API。

Multiplication of i, j is nothing but adding i, j times. i,j的乘积只不过是将i,j乘以。 this is java code, but you can take the logic from this. 这是Java代码,但是您可以从中获取逻辑。

    public int mul(int i, int j) {
        if(j==1) return i;
        return i + mul(i, j-1);
    }

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

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