Haskell一起列出了几个列表

时间:2016-10-25 05:39:19

标签: haskell

我想要List中一个元素的值,所以我做了

changePoint :: (Int,Int) -> [[[Char]]] -> [[Char]]

changePoint (x,y) maze = let 

          linelement = maze !! (y-1) 

-- value ["X"," "," ",...," ","X"]

          rowelement = chunksOf 1 $ head linelement 
-- type:[[a]]; value ["X"," "," "," "," "," "," "," "," "," "," "," "," ","X"]

          l = length rowelement
          list = take (x-1) rowelement

--          in take (x-1) rowelement  -- ["X"]  

           in take (x-1) rowelement ++ (["."] : (drop (x) rowelement))

我想附加列表"取(x-1)rowelement"和" ["。"]"和" drop(x)rowelement",列表的类型将是[[a]]

Couldn't match expected type ‘Char’ with actual type ‘[Char]’
  In the expression: "."
  In the first argument of ‘(:)’, namely ‘["."]’
  In the second argument of ‘(++)’, namely
    ‘(["."] : (drop (x) rowelement))’ Failed, modules loaded: none.

x = 2 .

我知道问题是" ["。"]"但我真的不知道如何修复它。

真正的回报应该是["X","."," "," ",..,"X" ]

2 个答案:

答案 0 :(得分:1)

在GHCI中,您可以使用:t somefunction获取somefunction的类型。

这里问题出在(:),让我们看看GHCI告诉我们的内容。

Prelude λ> :t (:)
(:) :: a -> [a] -> [a]

因此(:)获取aa列表并返回新列表。专门针对手头的用例,(:)的类型为[Char] -> [[Char]] -> [[Char]](因为a = [Char])。但["."]的类型为[[Char]],因此与(:)的预期不符。

现在,如果您使用take (x-1) rowelement ++ ("." : (drop (x) rowelement))(请注意[]周围缺少"."),该函数应该可以正常编译。

答案 1 :(得分:1)

使用:

(take (x-1) rowelement) ++ ["."] ++ (drop x rowelement)

或者

(take (x-1) rowelement) ++ ("." : (drop x rowelement))

[]不是必需的