递归:换种方式思考; How -> What.

函数式编程里没有循环,只有递归。那么如何用递归来实现平时很常见的循环呢?

那么我们就从最简单的开始来试试看,例如写几个string.h里面的函数:

unsigned int my_strlen(const char* str)
{
    if(*str=='\0')
        return 0;
    return my_strlen(str+1)+1;
}
char* my_strcpy(char* dest,const char* src)
{
    if(*src=='\0')
    {
        *dest=*src;
        return dest;
    }
    my_strcpy(dest+1,src+1);
    *dest=*src;
    return dest;
}
const char* my_strchr(const char* str,char chr)
{
    if(*str=='\0')
        return (const char*)0;
    if(*str==chr)
        return str;
    else
        return my_strchr(str+1,chr);
}
static unsigned int is_find(const char* s1,const char* s2)
{
    if(*s2=='\0')
        return 1;
    if(*s1!=*s2)
        return 0;
    return is_find(s1+1,s2+1);
}
const char* my_strstr(const char* s1,const char* s2)
{


    if(my_strlen(s1) < my_strlen(s2))
        return (const char*)0;
    if(is_find(s1,s2))
        return s1;
    return my_strstr(s1+1,s2);
}

例如入门的99乘法表:

void print(int a,int b)
{
    printf("%d*%d=%d ",a,b,a*b);
}
void print_const(int a,int b)
{
    if(a==b)
    {
        print(a,b);
        return;
    }
    print(a,b);
    print_const(a+1,b);
}
void print_line(int n)
{
    print_const(1,n);
    printf("\n");
}   
void print_mul(int n)
{   
    if(n==0)
        return;
    print_mul(n-1);
    print_line(n);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值