I've just got into Haskell a few days ago and I love it. I'm looking for some pointers and best practices on how to organise and write Haskell code specifically when it comes to managing errors, which I have done using Maybe
.
The following is an implementation of "select a list from a 2D list, take the last item from its nearest non empty left neighbour and put it at its head" which is going to be a sub-routine of a puzzle solver.
How can I improve the succinctness of my function? I notice that the more complex the logic of my code gets, it starts to be somewhat unreadable.
module Seq where
import Data.Maybe
{-
- Given a 2D list, select a list via 1-based index
- Transfer the last item of its immediate non blank
- left neighbour to its head.
- @param [[Int]] input 2D list
- @param Int index of target list
- @return the input 2D list after operation -}
pull :: Maybe [[Int]] -> Int -> Maybe [[Int]]
-- CASE : null input
pull Nothing _ = Nothing
-- CASE : nothing left to pull
pull (Just _) 1 = Nothing
pull (Just ([]:xss)) 2 = Nothing
-- CASE : index out of bounds
pull (Just [xs]) n = Nothing
-- CASE : currently nothing to pull
pull (Just ([]:xs:xss)) n
| p' == Nothing = Nothing
| otherwise = Just ([] : p'')
where
p' = pull (Just (xs:xss)) (n-1)
p''= fromJust p'
-- CASE : base case; immediate pull
pull (Just (xs:xs2:xss)) 2 = Just ((init xs) : ((last xs):xs2) : xss)
-- CASE : intermediary blank; split results
pull (Just (xs:[]:xss)) n
| p' == Nothing = Nothing
| otherwise = Just ((head p'') : [] : (tail p''))
where
p' = pull (Just (xs:xss)) (n-1)
p''= fromJust p'
-- CASE : typical recursion to destination
pull (Just (xs:xs2:xss)) n
| p' == Nothing = Nothing
| otherwise = Just (xs : p'')
where
p' = pull (Just (xs2:xss)) (n-1)
p''= fromJust p'
The following are test cases for the function:
-- pull (Just [[1,2],[],[3],[]]) 4 == Just [[1,2],[],[],[3]]
-- pull (Just [[1,2],[],[3],[]]) 3 == Just [[1],[],[2,3],[]]
-- pull (Just [[1,2],[],[3],[]]) 2 == Just [[1],[2],[3],[]]
-- pull (Just [[],[],[1,2,3],[]) 2 == Nothing
[[Int]]
. Why is so? \$\endgroup\$