代码之家  ›  专栏  ›  技术社区  ›  luke

Haskell将多个参数缩写为单个变量

  •  0
  • luke  · 技术社区  · 7 年前

    所以我有一个函数 必须 有某种类型。我的实现类似于以下内容:

    f :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int
    f t1 t2 t3 t4 t5 t6 t7 t8 t9
        = filterFirst checkFunc p
        where
            p = findAll [1..9]
            checkFunc = validate t1 t2 t3 t4 t5 t6 t7 t8 t9
    

    现在有没有办法把t值缩写为 或者类似的事情:

    f :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int
    f ts
        = filterFirst checkFunc p
        where
            p = findAll [1..9]
            checkFunc = validate ts
    

    一个让它看起来更干净的方法将会是惊人的。

    编辑: 更多细节

    validate :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> [Int] -> Bool
    validate t1 t2 t3 t4 t5 t6 t7 t8 t9 is =
        [t1, t2, t3, t4, t5, t6, t7, t8, t9] == sums is
    
    -- Calculates sums from specific indexes in list
    sums :: [Int] -> [Int]
    
    -- from https://stackoverflow.com/a/28904773/1218369
    filterFirst :: (a -> Bool) -> [a] -> [a]
    
    -- Find all possible permutations
    findAll :: [a] -> [[a]]
    -- Basically Data.List (permutations)
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   chepner    7 年前

    首先,让我们用一种更接近于构成 filterFirst 实际使用 t

    f t1 t2 t3 t4 t5 t6 t7 t8 t9 = let cf = validate t1 t2 t3 t4 t5 t6 t7 t8 t9
                                   in (flip filterFirst) (findAll [1..9]) cf
    

    http://pointfree.io

    f = ((((((((flip filterFirst (findAll [1..9]) .) .) .) .) .) .) .) .) . validate
    

    t型 定义中的名称。

    然而,我不认为这是对显式版本的改进。