我正在学习 Haskell,我正在做的一个练习是创建一个函数,该函数根据函数的返回值将列表划分为三个列表,以便为等于 1 的函数值获得第一个子列表,函数值的第二个子列表为 2,第三个子列表包含其他所有内容。
函数声明读取
partition3 :: (a -> Int) -> [a] -> ([a], [a], [a])
partition3 _ [] = []
Run Code Online (Sandbox Code Playgroud)
作为入门示例,请考虑
partition3 (\x -> mod x 5) [1..10] = ([1,6], [2,7], [3,4,5,8,9,10])
Run Code Online (Sandbox Code Playgroud)
现在,我已经对函数filterAny, isSuitable, removeIf,进行了编码isNotSuitable。完整代码如下:
filterAny :: [a -> Bool] -> [a] -> [a]
filterAny _ [] = []
filterAny ps (x:xs)
| isSuitable ps x = x : filterAny ps xs
| otherwise = filterAny ps xs
isSuitable :: [a -> …Run Code Online (Sandbox Code Playgroud) 我写了一个函数,递归计算整数n> 1的最小除数:
using System;
public class Program
{
public static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(SmallestDivisor(n));
}
public static int SmallestDivisor(int n)
{
return SmallestDivisor(n, 2);
}
public static int SmallestDivisor(int n, int d)
{
if (n%d == 0)
return d;
else
return SmallestDivisor(n, d+1);
}
}
Run Code Online (Sandbox Code Playgroud)
我的目标是构建一个递归函数,只接受整数n作为参数.是否有任何可能的替代方法来避免调用另一个辅助函数作为参数整数n和d?
我的目标是编写一个反转整数数字的递归程序.当我测试第一个元素时,代码可以工作.但是,它不适用于其他两种情况,例如reverse(456)它打印321654并reverse(731)打印321654137.我认为问题在于public static variable reverted.
有人可以帮我理解问题并修复它吗?
using System;
public class Program
{
public static void Main(string[] args)
{
reverse(123);
reverse(456);
reverse(731);
}
public static int reverted=0;
public static void reverse(int number)
{
if (number!=0)
{
int remainder = number % 10;
reverted = (reverted*10)+remainder;
reverse(number/10);
}
else
Console.WriteLine(reverted);
}
}
Run Code Online (Sandbox Code Playgroud)