是否可以在Haskell中编写没有显式参数的任何函数?

时间:2016-04-10 15:37:56

标签: haskell

例如,我有一个表tab = [(1,11), (2,22), (3,33)]和两个函数。第一个将把表和一个Integer作为参数,并用表中的值替换Integer。让我们假设整数将在桌面上。

replace :: [(Int, Int)] -> Int -> Int
replace t i = snd $ head [x | x <- t, fst x == i]

第二个函数将使用表中的值替换列表中1, 2, 3的所有出现次数。

replaceAll :: [(Int, Int)] -> [Int] -> [Int]

首先我得到了:

replaceAll = \tab lst -> foldl(\acc x -> acc ++ [replace tab x]) [] lst

然后,

replaceAll = \tab -> foldl(\acc x -> acc ++ [replace tab x]) []

有没有办法在没有lambda函数的情况下编写这个? 编辑:不需要使用折叠功能。

1 个答案:

答案 0 :(得分:2)

这对我有用

replaceAll index vals = map (replace index) vals

虽然我也喜欢删除params,但我认为如果你填写这个定义的参数,这会更容易理解....

class Program
{
    static void Main(string[] args)
    {
        const string text = "abcde321x zz";
        var morse = new Morse(text);
        Console.WriteLine(morse.Code);
    }
}

class Morse
{
    private static Dictionary<char, string> Codes = new Dictionary<char, string>()
    {
        {'1', ".----"}, {'2', "..---"}, {'3', "...--"}, {'4', "....-"},
        {'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."},
        {'9', "----."}, {'0', "-----"}
    };
    private string Message;
    public string Code
    {
        get
        {
            char firstDigit = this.Message.FirstOrDefault(c => char.IsDigit(c));
            return Codes.ContainsKey(firstDigit) ? Codes[firstDigit] : string.Empty;
        }
    }
    public Morse(string message)
    {
        this.Message = message;
    }
}
相关问题