0

I have a function that returns a list like this:

[ [1, 2, 3], [], [5], [5,6], []]

But I want to replace the empty lists with 0, so that it looks like this

[ [1, 2, 3], [0], [5], [5,6], [0]]

So far I have tried filter and map with little success. Can someone please point me in the right direction?

Here is the code in question:

knightPlace:: [Int] -> [[Int]]
knightPlace n = makeboard n

    where
    makeboard n =  [x | i<-[0..(length n -1 )], x <- [checkPos i]]
    -- checkPos add zero
    checkPos i = [j+1 | j<-[0..(length n -1 )], queenFilter n i j]
    -- filters all rows, cols and diags, also knights
    queenFilter n i j = and [n!!(i) == 0 && n!!(k) /=(j+1) && (n!!(k)==0 || (abs(n!!(k)-(j+1))/=abs(i-k))) && (n!!(k)==0 ||not( ((abs(i-k)==2)&& (abs(n!!(k)-(j+1))==1)) ||((abs(i-k)==1)&& (abs(n!!(k)-(j+1))==2))))       | k<-[0..(length n - 1)] ]

Called like

 knightPlace [0, 0, 6, 0, 0, 4, 0, 0]

3 Answers 3

5

Consider that if you have a function foo that can transform [] to [0] and return every other list untouched, map foo is the final function that you want.

Sign up to request clarification or add additional context in comments.

Comments

2

Replace xs with ys in l,

replaceWith :: [a] -> [a] -> [[a]]
replaceWith xs ys l = map (\x -> if x == xs then ys else x) l

In the case here,

replaceWith [] [0] [[1, 2, 3],[],[5],[5,6],[]]

Comments

2

Change your function with

knightPlace n = map (\x -> if null x then [0] else x) $ makeboard n

Also consider using pointfree style

knightPlace = map (\x -> if null x then [0] else x) . makeboard

2 Comments

Did you try to compile that last function in the comments? You should get a scope error. ;)
Oh right, I write it while on the train and didn't check it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.