dropWhile

dropWhile

Yet another staple for the functional programmer. You have a sequence of values and some predicate for those values. You want to remove the longest prefix of elements such that the predicate is true for each element. We’ll call this the dropWhile function. It accepts two arguments. The first is the sequence of values, and the second is the predicate function. The function does not change the value of the original sequence.
Your task is to implement the dropWhile function. If you’ve got a span function lying around, this is a one-liner! Alternatively, if you have a takeWhile function on your hands, then combined with the dropWhile function, you can implement the span function in one line. This is the beauty of functional programming: there are a whole host of useful functions, many of which can be implemented in terms of each other.

#include <stdio.h>
typedef bool (*Predicate)(const int*);

bool isOdd(const int *pvalue) {
    return *pvalue % 2;
}
bool isEven(const int *pvalue) {
    return !isOdd(pvalue);
}
int *dropWhile(
               const int *values, 
               size_t     count,
               Predicate  pred, 
               size_t     *pResultCount)
{
    const int *temp   = values;
    size_t count_temp = count;
    *pResultCount     =count_temp;
    while(pred(temp++)&&count_temp--)
        (*pResultCount)--;
    if(*pResultCount)
    {
        int* p=(int*)malloc((*pResultCount)*sizeof(int));
        if(p == NULL)
        {
            *pResultCount=0;
            return NULL;
        }
        memcpy(p,values+count-*pResultCount,(*pResultCount)*4);
        return p;
    }
}
int main()
{
    const int values[]  = { 2, 6, 4, 1, 1, 5, 4, 3 };
    size_t actualCount  = 0;
    int *p=dropWhile(values,sizeof(values)/4,isEven,&actualCount);
    free(p);
    p=NULL;
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值