Skip to content

Instantly share code, notes, and snippets.

@dschinkel
Last active September 10, 2018 20:00
Show Gist options
  • Save dschinkel/44cfa5eba35c0bc6c066d39a839e7f94 to your computer and use it in GitHub Desktop.
Save dschinkel/44cfa5eba35c0bc6c066d39a839e7f94 to your computer and use it in GitHub Desktop.
miniMax Algorithm in Elm - Tests - next move wins for row 2
module Scorer exposing (..)
import Array exposing (fromList, get, set)
-- below won't work, you can't do this in elm. You can't have two statements in the in of a let like this
nextBestMove : List Char -> Int
nextBestMove gameNode =
let
cells =
fromList gameNode
in
set 2 'X' cells
if ((get 0 cells == get 1 cells) && (get 1 cells == get 2 cells)) then 2 else 0
set 5 'X' cells
if ((get 3 cells == get 4 cells) && (get 4 cells == get 5 cells)) then 5 else 0
-- this also does not work
nextBestMove : List Char -> Int
nextBestMove gameNode =
let
cells =
fromList gameNode
set 2 'X' cells
set 5 'X' cells
in
if ((get 0 cells == get 1 cells) && (get 1 cells == get 2 cells)) then 2 else 0
if ((get 3 cells == get 4 cells) && (get 4 cells == get 5 cells)) then 5 else 0
{--|
Error:
I ran into something unexpected when parsing your code!
13| if ((get 0 cells == get 1 cells) && (get 1 cells == get 2 cells)) then 2 else 0
^
I am looking for one of the following things:
end of input
whitespace
--}
-- I then changed it to:
nextBestMove : List Char -> Int
nextBestMove gameNode =
let
cells =
fromList gameNode
set 2 'X' cells
set 5 'X' cells
in
if ((get 0 cells == get 1 cells) && (get 1 cells == get 2 cells)) then 2
else if ((get 3 cells == get 4 cells) && (get 4 cells == get 5 cells)) then 5 else 0
{--|
Error:
It looks like the keyword `in` is being used as a variable.
14| in
^
Rename it to something else.
--}
it "next move wins for row 2" <|
let
gameNode =
[ empty, empty, empty, markerX, markerX, empty, empty, empty, empty ]
cellFifthIndex =
5
nextMove =
Scorer.nextBestMove gameNode
in
expect nextMove to equal cellFifthIndex
{--|
The problem was this is an ML language so you can't
just make statements such as populating a value in an array
and call it day. An ML language always returns a reference to something either another function, another type
etc. In this case calling set on the array to set a value returns a new array. I wasn't doing anything with the
returned array and trying to check logic on the original array in the `in` (body) of my function
Here's how I changed it to work now below
--}
nextBestMove gameNode =
let
cells =
fromList gameNode
nextGameState1 =
set 2 'X' cells
nextGameState2 =
set 5 'X' cells
in
if (get 0 nextGameState1 == get 1 nextGameState1) && (get 1 nextGameState1 == get 2 nextGameState1) then
2
else if (get 3 nextGameState2 == get 4 nextGameState2) && (get 4 nextGameState2 == get 5 nextGameState2) then
5
else
0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment