Skip to content

Instantly share code, notes, and snippets.

@robkuz
Created May 25, 2016 12:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robkuz/3634334b4bc5a20953c775420430ffd4 to your computer and use it in GitHub Desktop.
Save robkuz/3634334b4bc5a20953c775420430ffd4 to your computer and use it in GitHub Desktop.
refactoring some convoluted error handling code
initial code with some really convoluted error handling.
The problem on this is that it must check for 2 different error cases and also return a different result in those error cases
dot :: Matrix -> Matrix -> Either MatrixError Number
dot (Matrix a sa) (Matrix b sb) = if areSimilarVectors sa sb then Right $ dot' a b else failed sa sb
where
areSimilarVectors s1 s2 = isVector s1 s2 && isSameSize s1 s2
dot' a b = _dot (join a) (join b)
isVector sa sb = fst sa == 1 && fst sb == 1
isSameSize sa sb = snd sa == snd sb
failed sa@(Tuple ax ay) sb@(Tuple bx by) =
if isVector sa sb then
if isSameSize sa sb then
Left $ UnexpectedError
else
Left $ InvalidVectorSize ay by
else
Left $ VectorsExpected
made better by aligning the `then` and the `else` branch with `Right` and `Left` and also removing the shadowing of the values
in the `where` clause
dot :: Matrix -> Matrix -> Either MatrixError Number
dot (Matrix a sa@(Tuple ax ay)) (Matrix b sb@(Tuple bx by)) = if isVector && isSameSize then Right (dot' a b) else Left $ failed
where
dot' a b = _dot (join a) (join b)
isVector = ax == 1 && bx == 1
isSameSize = ay == by
failed =
if isVector then
if isSameSize then
UnexpectedError
else
InvalidVectorSize ay by
else
VectorsExpected
nicer already
And then this
dot :: Matrix -> Matrix -> Either MatrixError Number
dot (Matrix a (Tuple ax ay)) (Matrix b (Tuple bx by))
| ax /= 1 && bx /= 1 = Left $ VectorsExpected
| ay /= by = Left $ InvalidVectorSize ay by
| otherwise = Right $ _dot (join a) (join b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment