Reputation: 316
I'm dabbling in some Haskell and have stumbled upon a bump in the road
I want to write a function that an AI uses to choose a row in a simple board game. The board in said game is represented by a list of integers. Like this:
board = [1,2,3,4,5]
The index + 1 of the numbers in the row on the board and the Int
itself is the number of pieces left on said row. How I aim to make this function work is by first to find the largest number in the list and then return (index + 1) of this number in the form of an IO Int
.
This is where I'm struggling since I can't seem to find any good answer to this online
This is what I'm working with so far:
-- Returns index of row with largest number along the number itself
aiHelper :: Board -> (Int, Int)
aiHelper xs = maximumBy (comparing fst) (zip xs [1..])
-- Returns row with largest number as IO Int
aiRow :: Board -> IO Int
aiRow xs = do
let y = snd $ aiHelper xs
return $ y
I'm not quite sure if this code does what I'm looking for, and is there an easier and cleaner solution to my code?
Upvotes: 2
Views: 118
Reputation: 233135
You can simplify the code like this:
aiRow :: Board -> IO Int
aiRow xs = return $ snd $ aiHelper xs
Or, by making an Eta reduction, to this:
aiRow :: Board -> IO Int
aiRow = return . snd . aiHelper
But, really, you don't need to return IO Int
. Why not just the following?
aiRow :: Board -> Int
aiRow = snd . aiHelper
At this point, however, you're probably below the Fairbairn threshold.
Upvotes: 5
Reputation: 16105
After Mark's proposal, aiRow
now does so little on its own that you might as well combine it with aiHelper
:
maximumIndex :: Ord a => [a] -> Int
maximumIndex = fst . maximumBy (comparing snd) . zip [1..]
(Switching fst
and snd
.)
Upvotes: 1