乘以不带+或* [英] Multiply without + or *
问题描述
我正在独自研究如何设计程序.我还没有完全掌握复杂的线性递归,所以我需要一些帮助.
I'm working my way through How to Design Programs on my own. I haven't quite grasped complex linear recursion, so I need a little help.
问题:
定义multiply
,它使用两个自然数n
和x
,并在不使用Scheme的*
的情况下生成n * x
.也从该定义中删除+
.
The problem:
Define multiply
, which consumes two natural numbers, n
and x
, and produces n * x
without using Scheme's *
. Eliminate +
from this definition, too.
直接带+号:
(define (multiply n m)
(cond
[(zero? m) 0]
[else (+ n (multiply n (sub1 m)))]))
(= (multiply 3 3) 9)
我知道要使用add1
,但是我不能递归.
I know to use add1
, but I can't it the recursion right.
谢谢.
推荐答案
将问题分为两个功能.首先,您需要一个将(add m n)
.基本情况是什么?当n为零时,返回m.什么是递归步骤?再次调用add
的结果加1,但递减n.您猜对了,add1
和sub1
会很有用.
Split the problem in two functions. First, you need a function (add m n)
which adds m to n. What is the base case? when n is zero, return m. What is the recursive step? add one to the result of calling add
again, but decrementing n. You guessed it, add1
and sub1
will be useful.
另一个功能(mul m n)
与之类似.基本情况是什么?如果m或n为零,则返回0.递归步骤是什么?将m添加(使用先前定义的函数)再次调用mul
的结果,但递减n.就是这样!
The other function, (mul m n)
is similar. What is the base case? if either m or n are zero, return 0. What is the recursive step? add (using the previously defined function) m to the result of calling mul
again, but decrementing n. And that's it!
这篇关于乘以不带+或*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!