简体   繁体   English

如何在 Haskell 中通过列表处理递归(转置操作)

[英]How to deal with recursing through a list in Haskell (transpose operation)

While I understand that there may be transpose or ZipList functions in Haskell, I am trying to build my own transpose function that will take n lists of equal length m and transpose them into m lists of length n .虽然我知道 Haskell 中可能有转置或 ZipList 函数,但我正在尝试构建我自己的转置函数,该函数将采用n个等长m 的列表并将它们转置为m个长度为n 的列表。

So far I have the function nearly working with the following code:到目前为止,我的功能几乎可以使用以下代码:

list = [[1,2,3],[4,5,6],[7,8,9]]

head' (x:xs) = x

head'' [] = []
head'' (xs:lxs) = head' xs:head'' lxs

tail' [] = []
tail' (x:xs) = xs

tail'' [] = []
tail'' (xs:lxs) = tail' xs:tail'' lxs

merge (xs:lxs) = (head' xs:head'' lxs):(merge (tail' xs:tail'' lxs))

and I get the following output when I run > merge list in ghci I get:当我在 ghci 中运行 > merge list时,我得到以下输出:

[[1,4,7],[2,5,8],[3,6,9],[*** Exception: list2.hs:16:1-16: Non-exhaustive patterns in function head'

which I am pretty sure means that the base case of the empty list on my head' function is missing.我很确定这意味着我head'的空列表的基本情况丢失了。 The list is transposed, just not closed.该列表已转置,只是未关闭。 How do I deal with that problem in this case?在这种情况下我该如何处理这个问题? I have an inkling that it might have to do with Maybe , but I'm having trouble implementing it that way.我有一种暗示,它可能与Maybe ,但我无法以这种方式实现它。

You need to add exit conditions:您需要添加退出条件:

merge [] = []
merge ([]:xss) = merge xss

map is all you need, in addition to the existing head and tail functions.除了现有的headtail功能之外, map就是您所需要的。 For simplicity, this assumes that the input is always a non-empty list (ie, xs might be [[],[],[]] , but never [] alone, so there's no problem with using head or tail .)为简单起见,这里假设输入始终是一个非空列表(即, xs可能是[[],[],[]] ,但绝不是单独的[] ,因此使用headtail没有问题。)

> map head list
[1,4,7]
> map tail list
[[2,3],[5,6],[8,9]]
> let foo xs = if null (head xs) then [] else map head xs : foo (map tail xs)
> foo list
[[1,4,7],[2,5,8],[3,6,9]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM