簡體   English   中英

Haskell,使用 function 和列表推導

[英]Haskell, using function with list comprehensions

我正在嘗試完成以下任務:

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)]

具體來說,我正在嘗試運行 function,獲取結果[[int]] ,然后 map 另一個 function 到該結果上。 哪個 haskell 顯然令人厭惡,我需要結合使用“lambda 函數”和其他我根本無法閱讀或理解的魔法來實現這一點。

有沒有什么簡單的方法可以做到這一點,不需要 7 個月的數學 function 語法課程?

如上所述,結果 board 是 [[int]],sequence 就是 [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.

看來您已經正確編寫了所有功能代碼,但沒有正確指定類型簽名。 trimBoard需要一個Board作為它的第一個參數,但是您已經將它傳遞給它c ,它是單行。

您可能抱怨的是,如果您將trimBoard傳遞給單行而不是完整的電路板,它應該可以很好地工作。 確實如此,您只需要學習如何說:

trimBoard :: [a] -> Int -> [a]

也就是說, trimBoard接受任何類型的列表和一個Int ,並返回相同類型的列表。 現在,您不僅限於傳遞Int列表的列表,而且一切正常。

您也可以省略 trimBoard 的類型簽名, trimBoard會推斷出這個,這是最通用的一個。 (但是編寫類型簽名並學習如何這樣做是件好事——事實上,通過實踐,這成為我在其他語言中非常懷念的無價工具)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM