I am trying to implement a function that collects all the values in an OrdTree in bfs order, and I also am having a hard time with this. Here is what I came with so far:
data OrdTree a = OrdTree a [OrdTree a] deriving (Show)
bfsTree :: OrdTree a -> [a]
bfsTree tree =
let
use2DList level list (OrdTree a []) = (list!!level)++[a]
use2DList currentLevel list (OrdTree a (branches)) =
foldl
(\tree theList -> use2DList (currentLevel+1) theList tree)
((list!!currentLevel)++[a])
branches
in
concat (use2DList 0 [] tree)
and obviously I am stuck with bunch of errors I haven't managed to figure out.
- I thought that since it's seemingly in scope, I should be able to use the
currentLevelvariable in foldl (specifically in the anonymous function), so am I? Is that okay? Or does it only have to work with the operands specified on the left of->? - I know that stuff is immutable, but list of lists.. if I append a value to one of the lists in a list it changes it, right? But what does such code return:
(list!!position)++[value]? - Would this be better if I tried to curry it like this (if I got that right):
foldl (use2DList (currentLevel+1)) (list!!currentLevel)++[a]) branchesor is that even worse?
Sorry if it's too much text, I am just really confused with this stuff.
Is this what you mean by bfs order?
Note that I've written
bfsto take a list ofOrdtree anot just a single tree.bfsis the list of trees at the current level.map val tsare the values at the current levelconcatMap children tsare all of the trees at the next levelUpdate: Here is some of the analysis I did on your code.
First of all it doesn't compile, so I started to remove code until I the compiler stopped complaining, and I arrived at:
Note there is no type signature on
bfsTree- we are going to have ghc tell us what the signature is, and it responds with:This is clearly not right - we want
OrdTree a -> [a]. The culprit, it turns out, is theconcat, so apparently the code should read:Now we can ask what the type signature of
use2DListis, and ghc (really ghc-mod) responds with:Now we have to figure out what the
foldlshould be.foldlhas the signature:Clearly we are folding over the branches, i.e.
t ~ OrdTree a, and the return type ofuse2DListis[a], sos ~ [a], so the first argument offoldlshould look like:Since your function begins
(\tree theList -> ...)it looks like you have to parameters swapped. And that's as far as I got.The main suggestions are:
:tcommand in ghci to interrogate the inferred types of functionsghcmod-vimplugin for vim or the haskell-mode plugin for emacs so you can interrogate sub-expressions in your program