小编Amo*_*moz的帖子

用折叠实现takeWhile

如何使用fold在Haskell中实现takeWhile函数?

takeWhile :: (a -> Bool) -> [a] -> [a]
Run Code Online (Sandbox Code Playgroud)

我尝试了类似于实现这样的过滤器的策略

filter :: (a -> Bool) -> [a] -> [a]
filter f = foldr (\x acc -> if f x then x : acc else acc) []
Run Code Online (Sandbox Code Playgroud)

但是当fx是假的时候我怎么能停下来?

haskell

3
推荐指数
1
解决办法
1473
查看次数

使用组合学改进计算外观的运行时间

我想计算有多少d位数不包括数字9,因为它可以很大,输出模10 ^ 9 + 7.

我运行以下代码t次,最多10 ^ 18位数字,我想解决功能应该很容易,对吧?那么也许阅读或印刷需要花费很多时间.

任何提示如何加快速度?

main = do
    contents <- getContents
    let (t:ds) = (map read . words) contents
    let ans = map solve ds
    sequence_ (map print ans)

solve :: Integer -> Integer
solve ds = mod (8 * 9^(ds - 1)) (10^9 + 7)
Run Code Online (Sandbox Code Playgroud)

algorithm haskell runtime combinatorics

2
推荐指数
1
解决办法
136
查看次数

Haskell 按索引更新子列表

在尝试学习 Haskell 时,我最近几次遇到过这个简单的模式:

假设我有一个列表,我想更新子列表中的所有元素,例如从索引 i 到 j。

我能想到的所有解决方案都让人感觉非常糟糕和糟糕,就像这个例子:

import qualified Data.Sequence as S

increment :: Int -> Int -> S.Seq Int -> S.Seq Int
increment i j sq | i <= j = increment (i + 1) to (S.adjust (+1) i sq)
                 | otherwise = sq
Run Code Online (Sandbox Code Playgroud)

我想如果我列出一份清单的话,情况会变得更糟。

有人知道一些简单的方法可以做到这一点吗?我尝试过搜索,也查看了标准库(Data.Array、Data.Vector 等),但它的编写方式有些让我的眼睛流血,我需要一些人性化的建议

haskell

2
推荐指数
1
解决办法
368
查看次数

Data.Bytestring长度给出错误的长度

我正在尝试制作一个程序,该程序使用输入字符串的长度作为计算的一部分。

我想使用ByteString来加快速度,因为输入字符串可能会非常长(注意:我真的不知道ByteString是什么,当输入很大时,我听说它的速度比String快)。

但是,当执行以下操作时:

import qualified Data.ByteString as B

main = do
    line <- B.getLine
    putStrLn . show $ B.length line
Run Code Online (Sandbox Code Playgroud)

如果我要传递字符串:10888869450418352160768000000

我得到30,但长度为29。

有人知道为什么吗?

haskell

1
推荐指数
1
解决办法
51
查看次数

如何知道推力的结果中有多少个元素::partition_copy

我正在尝试使用推力库的 partition_copy 函数对数组进行分区。

我看过传递指针的例子,但我需要知道每个分区中有多少元素。

我尝试过的是将设备向量作为 OutputIterator 参数传递,如下所示:

#include <thrust/device_vector.h>
#include <thrust/device_ptr.h>
#include <thrust/partition.h>

struct is_even {
    __host__ __device__ bool operator()(const int &x) {
        return (x % 2) == 0;
    }
};

int N;
int *d_data;
cudaMalloc(&d_data, N*sizeof(int));

//... Some data is put in the d_data array

thrust::device_ptr<int> dptr_data(d_data);

thrust::device_vector<int> out_true(N);
thrust::device_vector<int> out_false(N);

thrust::partition_copy(dptr_data, dptr_data + N, out_true, out_false, is_even());
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时出现此错误:

error: class "thrust::iterator_system<thrust::device_vector<int, thrust::device_allocator<int>>>" has no member "type"
      detected during instantiation of "thrust::pair<OutputIterator1, OutputIterator2> thrust::partition_copy(InputIterator, InputIterator, OutputIterator1, OutputIterator2, Predicate) [with …
Run Code Online (Sandbox Code Playgroud)

c++ cuda gpu thrust

1
推荐指数
1
解决办法
158
查看次数

标签 统计

haskell ×4

algorithm ×1

c++ ×1

combinatorics ×1

cuda ×1

gpu ×1

runtime ×1

thrust ×1