Haskell,将函数与列表推导一起使用

RNP*_*NPF 0 haskell

我正在尝试完成以下任务:

slice :: Int -> Int -> [a] -> [a]
slice from to xs = take (to - from + 1) (drop from xs)

trimBoard :: Board -> Int -> Board
trimBoard s y = slice ((y*3)) (((y+1)*3)-1) s

getBox :: Board -> Int -> Int -> [Sequence]
getBox s y x = [ (trimBoard c x) | c <- (trimBoard s y)]
Run Code Online (Sandbox Code Playgroud)

具体来说,我试图运行一个函数,获取结果[[int]],然后将另一个函数映射到该结果上。这似乎令人讨厌,我需要使用“ lambda函数”和我完全无法阅读或理解的其他巫术的某种组合来进行这种适应。

有没有简单的方法可以做到,而这不需要7个月的数学函数语法课程?

如上所述,结果board是[[int]],而序列只是[int]。

它产生的错误是

sudoku.hs:139:19: error:
    • Couldn't match type ‘[Int]’ with ‘Int’
      Expected type: Sequence
        Actual type: Board
    • In the expression: (trimBoard c x)
      In the expression: [(trimBoard c x) | c <- (trimBoard s y)]
      In an equation for ‘getBox’:
          getBox s y x = [(trimBoard c x) | c <- (trimBoard s y)]

sudoku.hs:139:29: error:
    • Couldn't match type ‘Int’ with ‘[Int]’
      Expected type: Board
        Actual type: Sequence
    • In the first argument of ‘trimBoard’, namely ‘c’
      In the expression: (trimBoard c x)
      In the expression: [(trimBoard c x) | c <- (trimBoard s y)] Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud)

luq*_*qui 5

It seems you have written all your functional code correctly but have not correctly specified your type signatures. trimBoard expects a Board as its first argument, but you have passed it c which is a single row.

您可能会抱怨的是,trimBoard如果您将其传递给一行而不是一整块板,那么它应该可以很好地工作。确实如此,您只需要学习怎么说:

trimBoard :: [a] -> Int -> [a]
Run Code Online (Sandbox Code Playgroud)

这样,它将trimBoard获取任何类型的列表和一个Int,并返回相同类型的列表。现在,您不仅可以传递的列表Int,而且一切正常。

您还可以省略的类型签名,trimBoard而Haskell可以推断出这是最通用的一种。(但是写类型签名并学习如何做是很好的-实际上,通过实践,这成为了我用其他语言非常想念的无价工具)。