Exception: Prelude.head: empty list in Haskell - haskell

I can't figure out why I'm getting this error. I have already read all the questions already asked about this error and I don't have any of those issues. Can someone please help. The comments are the hard code for the given example so we can use a top-down approach. When I get done with a function I comment out the hard code. I have only implemented the first 2 functions. In ghci when you run the file, type 'main', if it prints true the code is working. When I test both functions separately they return true but together they return the above error.
import Data.List ((\\), sort)
type Board = [[Int]]
inputBoard :: Board
inputBoard =
[[5,3,0, 0,7,0, 0,0,0],
[6,0,0, 1,9,5, 0,0,0],
[0,9,8, 0,0,0, 0,6,0],
[8,0,0, 0,6,0, 0,0,3],
[4,0,0, 8,0,3, 0,0,1],
[7,0,0, 0,2,0, 0,0,6],
[0,6,0, 0,0,0, 2,8,0],
[0,0,0, 4,1,9, 0,0,5],
[0,0,0, 0,8,0, 0,7,9]]
solvedBoard :: Board
solvedBoard =
[[5,3,4, 6,7,8, 9,1,2],
[6,7,2, 1,9,5, 3,4,8],
[1,9,8, 3,4,2, 5,6,7],
[8,5,9, 7,6,1, 4,2,3],
[4,2,6, 8,5,3, 7,9,1],
[7,1,3, 9,2,4, 8,5,6],
[9,6,1, 5,3,7, 2,8,4],
[2,8,7, 4,1,9, 6,3,5],
[3,4,5, 2,8,6, 1,7,9]]
type Coords = (Int,Int)
type BoardElement = (Coords,Int)
inputBoardElements :: [BoardElement]
inputBoardElements =
[((0,0),5),((0,1),3),((0,4),7),((1,0),6),((1,3),1),((1,4),9),((1,5),5),
((2,1),9),((2,2),8),((2,7),6),((3,0),8),((3,4),6),((3,8),3),((4,0),4),
((4,3),8),((4,5),3),((4,8),1),((5,0),7),((5,4),2),((5,8),6),((6,1),6),
((6,6),2),((6,7),8),((7,3),4),((7,4),1),((7,5),9),((7,8),5),((8,4),8),
((8,7),7),((8,8),9)]
inputBoardEmpty :: [Coords]
inputBoardEmpty =
[(0,2),(0,3),(0,5),(0,6),(0,7),(0,8),(1,1),(1,2),(1,6),(1,7),(1,8),
(2,0),(2,3),(2,4),(2,5),(2,6),(2,8),(3,1),(3,2),(3,3),(3,5),(3,6),
(3,7),(4,1),(4,2),(4,4),(4,6),(4,7),(5,1),(5,2),(5,3),(5,5),(5,6),
(5,7),(6,0),(6,2),(6,3),(6,4),(6,5),(6,8),(7,0),(7,1),(7,2),(7,6),
(7,7),(8,0),(8,1),(8,2),(8,3),(8,5),(8,6)]
solvedBoardElements :: [BoardElement]
solvedBoardElements =
[((0,0),5),((0,1),3),((0,2),4),((0,3),6),((0,4),7),((0,5),8),((0,6),9),
((0,7),1),((0,8),2),((1,0),6),((1,1),7),((1,2),2),((1,3),1),((1,4),9),
((1,5),5),((1,6),3),((1,7),4),((1,8),8),((2,0),1),((2,1),9),((2,2),8),
((2,3),3),((2,4),4),((2,5),2),((2,6),5),((2,7),6),((2,8),7),((3,0),8),
((3,1),5),((3,2),9),((3,3),7),((3,4),6),((3,5),1),((3,6),4),((3,7),2),
((3,8),3),((4,0),4),((4,1),2),((4,2),6),((4,3),8),((4,4),5),((4,5),3),
((4,6),7),((4,7),9),((4,8),1),((5,0),7),((5,1),1),((5,2),3),((5,3),9),
((5,4),2),((5,5),4),((5,6),8),((5,7),5),((5,8),6),((6,0),9),((6,1),6),
((6,2),1),((6,3),5),((6,4),3),((6,5),7),((6,6),2),((6,7),8),((6,8),4),
((7,0),2),((7,1),8),((7,2),7),((7,3),4),((7,4),1),((7,5),9),((7,6),6),
((7,7),3),((7,8),5),((8,0),3),((8,1),4),((8,2),5),((8,3),2),((8,4),8),
((8,5),6),((8,6),1),((8,7),7),((8,8),9)]
main :: IO ()
main = print (sudoku inputBoard == solvedBoard)
sudoku :: Board -> Board
sudoku [] = []
sudoku b =
let bde = fst (toElements b)
cd = snd (toElements b)
allboards = sudokuElements [bde] cd
in fromElements (head allboards)
--sudoku b
--| b == inputBoard = solvedBoard
--| otherwise = error "sudoku not implemented"
sudokuElements :: [[BoardElement]] -> [Coords] -> [[BoardElement]]
sudokuElements a [] = a
sudokuElements [] _ = []
sudokuElements (be:bes) (cd:cds) =
let xs = validVals be cd
temp = [[(cd,x)] | x <- xs]
in sudokuElements temp cds
-- | head bes == inputBoardElements && empty == inputBoardEmpty =
-- [solvedBoardElements]
-- | otherwise = error "sudokuElements not implemented"
validVals :: [BoardElement] -> Coords -> [Int]
validVals bes rc
| bes == tail solvedBoardElements && rc==(8,6) = [1]
| bes \\ solvedBoardElements == [] = [1..9]
| otherwise = []
toElements :: Board -> ([BoardElement],[Coords])
toElements b
| b==inputBoard = (inputBoardElements, inputBoardEmpty)
| otherwise = error "toElements not implemented"
fromElements :: [BoardElement] -> Board
fromElements bes
| sort bes == solvedBoardElements = solvedBoard
| otherwise = error "fromElements not implemented"

The issue is that allBoards/the call to sudokuElements is returning an empty list.
Without seeing the entire program, it's hard to give you an exact reason why this might be.
I recommend avoiding the use of head in general as it is a partial function. Instead, use pattern matching.
In your case, this
fromElements (head allBoards)
can be rewritten as
case allBoards of
[] -> error "allBoards returned an empty list." -- Or whatever
(first:_) -> fromElements first

Related

How do you create quickCheck properties with a Property output in Haskell?

How do you create a property that checks that all solutions provided are valid solutions, I need it to output as a Property, but I'm unsure how to do that, I only understand how to do Bool outputs for quickCheck properties. See below for my attempt, and the general idea of how I want it to function:
solve :: Sudoku -> Maybe Sudoku
solve s = solve' (blanks s) s
solve' :: [Pos] -> Sudoku -> Maybe Sudoku
solve' blankl s
| not (isOkay s) = Nothing
| isFilled s = Just s
| otherwise = listToMaybe [fromJust sol | n <- [1..9],
let sol = solve' (tail blankl) (update s (head blankl) (Just n)),
sol /= Nothing]
isSolutionOf :: Sudoku -> Sudoku -> Bool
isSolutionOf s1 s2 =
isOkay s1
&& isFilled s1
&& and [ a == b || b == Nothing |
(a,b) <- zip (concat (rows s1)) (concat (rows s2)) ]
prop_SolveSound :: Sudoku -> Property
prop_SolveSound s
| solution == Nothing = True
| otherwise = isSolutionOf (fromJust solution) s where
solution = solve s
Any help is much appreciated, I guess what I'm asking is how can you convert the - quite clearly - Bool output from prop_SolveSound to a Property output?
At the very simplest, you can use property method to convert e.g. Bool to Property. I suggest to look at the instances of Testable class, and try to understand what each of them does, and how it can be used.
Or you can be more sophisticated and use some other functions returning Property, e.g. ===. That might be tricky in your example.
One quite useful function, is counterexample. It allows you to print additional output, when property doesn't hold. For example, it's used to implement ===:
(===) :: (Eq a, Show a) => a -> a -> Property
x === y =
counterexample (show x ++ interpret res ++ show y) res
where
res = x == y
interpret True = " == "
interpret False = " /= "
As this is an assignment, I'm not giving you any more hints.

Return the item at the specified position in list

I'm trying to find out en element at a particular position in a list using recursive function. The function takes 2 parameter, an int & list. int is the position of the item in the list. I have specified 2 cases, 1st case for empty list provided and 2nd case for non- empty list.
.hs code
findKthElem :: Ord a => Int -> [a] -> a
findKthElem x [] = error "empty list provided"
findKthElem x (y:ys) = if x==1 then y else findKthElem (x-1) ys
Input
*Main> findKthElem 0 [1..99]
Output
** Exception: empty list provided
Expected Output
1
Since I'm a newbie in Haskell I can't understand where I'm going wrong. Please Help.
An approach using guards to match against different index values:
findKthElem :: Ord a => Int -> [a] -> a
findKthElem _ [] = error "empty list provided"
findKthElem i (x:xs) | i < 0 = error "invalid index"
| i == 0 = x
| otherwise = findKthElem (i - 1) xs
You can also use the Maybe monad to remain error free:
findKthElem :: Ord a => Int -> [a] -> Maybe a
findKthElem _ [] = Nothing
findKthElem i (x:xs) | i < 0 = Nothing
| i == 0 = Just x
| otherwise = findKthElem (i - 1) xs

How to get a solution to a puzzle having a function that gives the next possible steps in Haskell

I'm solving the Brigde and torch problem
in Haskell.
I wrote a function that given a state of the puzzle, as in which people have yet to cross and those who have crossed, gives back a list of all possible moves from one side to the other (moving two people forwards and one person backwards).
module DarkBridgeDT where
data Crossing = Trip [Float] [Float] Float deriving (Show)
data RoundTrip = BigTrip Crossing Crossing deriving (Show)
trip :: [Float] -> [Float] -> Float -> Crossing
trip x y z = Trip x y z
roundtrip :: Crossing -> Crossing -> RoundTrip
roundtrip x y = BigTrip x y
next :: Crossing -> [RoundTrip]
next (Trip [] _ _) = []
next (Trip (a:b:[]) s _ )
|a>b = [BigTrip (Trip [] (a:b:s) a) (Trip [] [] 0)]
|otherwise = [BigTrip (Trip [] (b:a:s) b) (Trip [] [] 0)]
next (Trip d s _) = [BigTrip (Trip [x,z] (i:j:s) j) b | i <- d, j <- d, i < j, x <- d, z <- d, x < z, z /= i, z /= j, x /= z, x /= i, x /= j, b <- (back [x,z] (i:j:s))]
where
back [] s = []
back d s = [Trip (i:d) (filter (/= i) s) i | i <- s]
Now I need a function that given a state as the one above and a maximum amount of time gives back all possible solutions to the puzzle in less than that given time.
All I have for that is this:
cross :: Crossing -> Float -> [[RoundTrip]]
cross (Trip [] _ _) _ = []
cross (Trip _ _ acu) max
| acu > max = []
cross (Trip a b acu) max = map (cross (map (crec) (next (Trip a b acu)) acu)) max
where
crec (BigTrip (Trip _ _ t1) (Trip a b t2)) acu = (Trip a b (t1+t2+acu))
Of course that doesn't compile, the 5th line is the one that's driving me insane. Any input?
Edit:
The cross function is meant to apply the next function to every result of the last nextfunction called.
If the first result of next was something like: [A,B,C,D] then it would call next on A B C and D to see if any or all of those get to a solution in less than max (A B C and D would be Crossings inside which contain the floats that are the time that ads up and is compared to max).
My data structure is
Crossing: Contains the first side of the bridge (the people in it represented by the time they take to cross the bridge) the other side of the bridge (the same as the other) and a time that represents the greatest time that last crossed the bridge (either the greatest of the two in the first crossing or the only one in the second) or the amount of time acumulated crossing the bridge (in the cross function).
RoundTrip: Represents two crossings, the first and the second, the one getting to safety and the one coming back to danger.
cross (Trip [1,2,5,10] [] 0) 16 should give an empty list for there is no solution that takes less than 17 minutes (or whatever time unit).
cross (Trip [1,2,5,10] [] 0) 17 should give the normal solution to the puzzle as a list of roundtrips.
I hope that makes it clearer.
Edit2:
I finally got it. I read Carsten's solution before I completed mine and we laid it out practically the same. He used fancier syntax and more complex structures but it's really similar:
module DarkBridgeST where
data Torch = Danger | Safety deriving (Eq,Show)
data State = State
[Float] -- people in danger
[Float] -- people safe
Torch -- torch position
Float -- remaining time
deriving (Show)
type Crossing = [Float]
classic :: State
classic = State [1,2,5,10] [] Danger 17
next :: State -> [Crossing] -- List all possible moves
next (State [] _ _ _) = [] -- Finished
next (State _ [] Safety _) = [] -- No one can come back
next (State danger _ Danger rem) = [[a,b] | a <- danger, b <- danger, a /= b, a < b, max a b <= rem]
next (State _ safe Safety rem) = [[a] | a <- safe, a <= rem]
cross :: State -> Crossing -> State -- Crosses the bridge depending on where the torch is
cross (State danger safe Danger rem) cross = State (taking cross danger) (safe ++ cross) Safety (rem - (maximum cross))
cross (State danger safe Safety rem) cross = State (danger ++ cross) (taking cross safe) Danger (rem - (maximum cross))
taking :: [Float] -> [Float] -> [Float]
taking [] d = d
taking (x:xs) d = taking xs (filter (/=x) d)
solve :: State -> [[Crossing]]
solve (State [] _ _ _) = [[]]
solve sf = do
c <- next sf
let sn = cross sf c
r <- solve sn
return (c:r)
All in all thanks everyone. I'm new to Haskell programming and this helped me understand a lot of things. I hope this post can also help someone starting haskell like me one day :)
I'm not going to leave much of your code intact here.
The first problems are with the data structures. Crossing doesn't actually represent anything to do with crossing the bridge, but the state before or after a bridge crossing. And you can't use RoundTrip because the number of bridge crossings is always odd.
I'm renaming the data structure I'm actually keeping, but I'm not keeping it unmodified.
data Bank = Danger | Safety deriving (Eq,Show)
data PuzzleState = PuzzleState
[Float] -- people still in danger
[Float] -- people on the safe bank
Bank -- current location of the torch
Float -- remaining time
type Crossing = ([Float],Bank)
Modifying/writing these functions is left as an exercise for the reader
next :: PuzzleState -> [Crossing] -- Create a list of possible crossings
applyCrossing :: PuzzleState -> Crossing -> PuzzleState -- Create the next state
Then something like this function can put it all together (assuming next returns an empty list if the remaining time is too low):
cross (PuzzleState [] _ _ _) = [[]]
cross s1 = do
c <- next s1
let s2 = applyCrossing s1 c
r <- cross s2
return $ c : r
Just for the fun, an approach using a lazy tree:
import Data.List
import Data.Tree
type Pawn = (Char, Int)
data Direction = F | B
data Turn = Turn {
_start :: [Pawn],
_end :: [Pawn],
_dir :: Direction,
_total :: Int
}
type Solution = ([String], Int)
-- generate a tree
mkTree :: [Pawn] -> Tree Turn
mkTree p = Node{ rootLabel = s, subForest = branches s }
where s = Turn p [] F 0
-- generates a node for a Turn
mkNode :: Turn -> Tree Turn
mkNode t = Node{ rootLabel = t, subForest = branches t }
-- next possible moves
branches :: Turn -> [Tree Turn]
-- complete
branches (Turn [] e d t) = []
-- moving forward
branches (Turn s e F t) = map (mkNode.turn) (next s)
where
turn n = Turn (s\\n) (e++n) B (t+time n)
time = maximum . map snd
next xs = [x| x <- mapM (const xs) [1..2], head x < head (tail x)]
-- moving backward
branches (Turn s e B t) = map (mkNode.turn) e
where
turn n = Turn (n:s) (delete n e) F (t+time n)
time (_,b) = b
solve :: Int -> Tree Turn -> [Solution]
solve limit tree = solve' [] [] limit tree
where
solve' :: [Solution] -> [String] -> Int -> Tree Turn -> [Solution]
solve' sols cur limit (Node (Turn s e d t) f)
| and [t <= limit, s == []] = sols ++ [(cur++[step],t)]
| t <= limit = concat $ map (solve' sols (cur++[step]) limit) f
| otherwise = []
where step = "[" ++ (v s) ++ "|" ++ (v e) ++ "]"
v = map fst
Then you you can get a list of solutions:
solve 16 $ mkTree [('a',2), ('b',4), ('c',8)]
=> [(["[abc|]","[c|ab]","[ac|b]","[|bac]"],14),(["[abc|]","[c|ab]","[bc|a]","[|abc]"],16),(["[abc|]","[b|ac]","[ab|c]","[|cab]"],14),(["[abc|]","[a|bc]","[ba|c]","[|cab]"],16)]
Or also generate a tree of solutions:
draw :: Int -> Tree Turn -> Tree String
draw limit (Node (Turn s e d t) f)
| t > limit = Node "Time Out" []
| s == [] = Node ("Complete: " ++ step) []
| otherwise = Node step (map (draw limit) f)
where step = "[" ++ (v s) ++ "|" ++ (v e) ++ "]" ++ " - " ++ (show t)
v = map fst
Then:
putStrLn $ drawTree $ draw 16 $ mkTree [('a',2), ('b',4), ('c',8)]
Will result in:
[abc|] - 0
|
+- [c|ab] - 4
| |
| +- [ac|b] - 6
| | |
| | `- Complete: [|bac] - 14
| |
| `- [bc|a] - 8
| |
| `- Complete: [|abc] - 16
|
+- [b|ac] - 8
| |
| +- [ab|c] - 10
| | |
| | `- Complete: [|cab] - 14
| |
| `- [cb|a] - 16
| |
| `- Time Out
|
`- [a|bc] - 8
|
+- [ba|c] - 12
| |
| `- Complete: [|cab] - 16
|
`- [ca|b] - 16
|
`- Time Out

Implementation of a program in which characters of a string repeated certain times in haskell

This is a question from my homework thus tips would be much likely appreciated.
I am learning Haskell this semester and my first assignment requires me to write a function that inputs 2 string (string1 and string2) and returns a string that is composed of (the repeated) characters of first string string1 until a string of same length as string2 has been created.
I am only allowed to use the Prelude function length.
For example: take as string1 "Key" and my name "Ahmed" as string2 the function should return "KeyKe".
Here is what I've got so far:
makeString :: Int -> [a] -> [a]
makeString val (x:xs)
| val > 0 = x : makeString (val-1) xs
| otherwise = x:xs
Instead of directly giving it two strings i am giving it an integer value (since i can subtitute it for length later on), but this is giving me a runtime-error:
*Main> makeString 8 "ahmed"
"ahmed*** Exception: FirstScript.hs: (21,1)-(23,21) : Non-exhaustive patterns in function makeString
I think it might have something to do my list running out and becoming an empty list(?).
A little help would be much appreciated.
I think this code is enough to solve your problem:
extend :: String -> String -> String
extend src dst = extend' src src (length dst)
where
extend' :: String -> String -> Int -> String
extend' _ _ 0 = []
extend' [] src size = extend' src src size
extend' (x:xs) src size = x : extend' xs src (size - 1)
The extend' function will cycle the first string until is is consumed then will begin to consume it again.
You can also make it using take and cycle like functions:
repeatString :: String -> String
repeatString x = x ++ repeatString x
firstN :: Int -> String -> String
firstN 0 _ = []
firstN n (x:xs) = x : firstN ( n - 1 ) xs
extend :: String -> String -> String
extend src dst = firstN (length dst) (repeatString src)
or a more generic version
repeatString :: [a] -> [a]
repeatString x = x ++ repeatString x
firstN :: (Num n, Eq n ) => n -> [a] -> [a]
firstN 0 _ = []
firstN n (x:xs) = x : firstN ( n - 1 ) xs
extend :: [a] -> [b] -> [a]
extend _ [] = error "Empty target"
extend [] _ = error "Empty source"
extend src dst = firstN (length dst) (repeatString src)
which is capable of taking any type of lists:
>extend [1,2,3,4] "foo bar"
[1,2,3,4,1,2,3]
Like Carsten said, you should
handle the case when the list is empty
push the first element at the end of the list when you drop it.
return an empty list when n is 0 or lower
For example:
makeString :: Int -> [a] -> [a]
makeString _ [] = [] -- makeString 10 "" should return ""
makeString n (x:xs)
| n > 0 = x:makeString (n-1) (xs++[x])
| otherwise = [] -- makeString 0 "key" should return ""
trying this in ghci :
>makeString (length "Ahmed") "Key"
"KeyKe"
Note: This answer is written in literate Haskell. Save it as Filename.lhs and try it in GHCi.
I think that length is a red herring in this case. You can solve this solely with recursion and pattern matching, which will even work on very long lists. But first things first.
What type should our function have? We're taking two strings, and we will repeat the first string over and over again, which sounds like String -> String -> String. However, this "repeat over and over" thing isn't really unique to strings: you can do that with every kind of list, so we pick the following type:
> repeatFirst :: [a] -> [b] -> [a]
> repeatFirst as bs = go as bs
Ok, so far nothing fancy happened, right? We defined repeatFirst in terms of go, which is still missing. In go we want to exchange the items of bs with the corresponding items of as, so we already know a base case, namely what should happen if bs is empty:
> where go _ [] = []
What if bs isn't empty? In this case we want to use the right item from as. So we should traverse both at the same time:
> go (x:xs) (_:ys) = x : go xs ys
We're currently handling the following cases: empty second argument list, and non-empty lists. We still need to handle the empty first argument list:
> go [] ys =
What should happen in this case? Well, we need to start again with as. And indeed, this works:
> go as ys
Here's everything again at a single place:
repeatFirst :: [a] -> [b] -> [a]
repeatFirst as bs = go as bs
where go _ [] = []
go (x:xs) (_:ys) = x : go xs ys
go [] ys = go as ys
Note that you could use cycle, zipWith and const instead if you didn't have constraints:
repeatFirst :: [a] -> [b] -> [a]
repeatFirst = zipWith const . cycle
But that's probably for another question.

Haskell: Expected Laziness, Why is this Evaluated?

I have a function sideH which runs the risk of Prelude.head []. Hence, I have written it using Maybe, to avoid this:
sideH :: Residue -> Maybe (Atom, Atom)
sideH res
-- Make sure the elements exist
| nits /= [] && cars /= [] && oxys /= [] = Just (newH1, newH2)
| otherwise = Nothing where
...
The above works exactly as expected, without error. Now, in the function which calls sideH (which is not a do construct), I must handle the situation that sideH returns Nothing:
callerFunc :: [Residue] -> Aromatic -> [(Double, Double)]
callerFunc [] _ = []
callerFunc (r:rs) aro
-- Evaluate only if there is something to evaluate
| newHs /= Nothing = (newH1Pos, newH2Pos)
| otherwise = callerFunc rs aro where
newHs = sideH r
newH1Pos = atomPos $ fst $ fromJust newHs
newH2Pos = atomPos $ snd $ fromJust newHs
If I try to evaluate newH1Pos or newH2Pos when newH = Nothing, it will fail because fromJust Nothing is an error. However, I expect this to never happen. I expect the callerFunc to evaluate newHs, which is either Just something or Nothing. If it is Nothing, then the callerFunc will go to its next step without ever evaluating newH1Pos or newH2Pos. This does not appear to be the case. I get an *** Exception: Maybe.fromJust: Nothing error exactly where I would expect newHs to return Nothing.
I was asked for more code. I am trying to come up with a minimum situation that reproduces the error, but in the mean time, here is the complete problematic callerFunc code.
-- Given a list of residues and an aromatic, find instances where there
-- is a Hydrogen bond between the aromatic and the Hydrogens on Gln or Asn
callerFunc :: [Residue] -> Aromatic -> [(Double, Double)]
callerFunc [] _ = []
callerFunc (r:rs) aro
-- GLN or ASN case
| fst delR <= 7.0 && (resName r == gln || resName r == asn) &&
newHs /= Nothing && snd delR <= 6.0 =
[(snd delR, fst delR)] ++ hBondSFinder rs aro
| otherwise = hBondSFinder rs aro where
-- Sidechain identifying strings
gln = B.pack [71, 76, 78]
asn = B.pack [65, 83, 78]
-- Get the location of the Hydrogens on the residue's sidechain
newHs = sideH r
newH1Pos = atomPos $ fst $ fromJust newHs
newH2Pos = atomPos $ snd $ fromJust newHs
-- Get the location of the Nitrogen on the mainchain of the Residue
ats = resAtoms r
backboneNPos = atomPos $ head $ getAtomName ats "N"
hNVect1 = Line2P {lp1 = newH1Pos, lp2 = backboneNPos}
hNVect2 = Line2P {lp1 = newH2Pos, lp2 = backboneNPos}
interPoint1 = linePlaneInter (aroPlane aro) hNVect1
interPoint2 = linePlaneInter (aroPlane aro) hNVect2
delR = minimum [(interPoint1 `dist` newH1Pos, delr1),
(interPoint2 `dist` newH2Pos, delr2)]
delr1 = interPoint1 `dist` (aroCenter aro)
delr2 = interPoint2 `dist` (aroCenter aro)
I know this is a painful code dump. I am trying to whittle it down.
The answer to this question (asked in the comments) doesn't fit in a comment: "I am not sure how I would use pattern matching, here, to remove these if statement.".
Like this, for example, though there are still some code smells left that could likely be improved with some additional refactoring:
sideH :: Residue -> Maybe (Atom, Atom)
sideH res = case (nits, cars, oxys) of
(_:_, _:_, _:_) -> Just (newH1, newH2)
_ -> Nothing
where
...
If you have flexible morals, you might try something like this:
sideH :: Residue -> Maybe (Atom, Atom)
sideH res = do
_:_ <- return nits
_:_ <- return cars
_:_ <- return oxys
return (newH1, newH2)
where
...
Again, both of these code samples can likely be improved about tenfold if there's a bit more context and code available to make recommendations for.

Resources