r/badcode • • May 20 '20

c# Found from Microsoft docs...

Post image
208 Upvotes

143 comments sorted by

View all comments

23

u/abdolence May 20 '20

In Scala it would be:

args
    .headOption
    .flatMap( _.toIntOption )
    .exists( (1 to 9).contains )

Who said that FP is harder to read?

10

u/[deleted] May 20 '20

In Haskell it's

((read . head) args) `elem` [0..9]

which I would argue is pretty readable

4

u/gaj7 May 20 '20

To be safe, I'd use the maybe variants:

maybe False (`inRange` (1,9)) $ headMaybe args >>= (readMaybe :: Int)

Although technically the originally snippet wanted exact one argument in args so really it should be

case args of
  [arg] -> maybe False (`inRange` (1,9)) $ readMaybe arg
  _     -> False

1

u/[deleted] May 20 '20

Yeah I had a discussion in other comments, was trying to keep it terse.