Compare commits

...

171 Commits

Author SHA1 Message Date
08c1e3e068 gp loop errors out, time to debug this 2025-03-08 23:49:22 -06:00
06eac6eba4 I don't think quickcheck is the play 2025-03-08 20:14:37 -06:00
0fd2c2e5dd more instructions and start of int tests 2025-03-08 03:40:26 -06:00
95786d0c93 fixed verbose hanging problem 2025-03-07 21:44:44 -06:00
17c767c43c hangs on a verbose check on nix 2025-03-07 21:10:44 -06:00
5d11e75566 add lin alg credit 2025-03-07 16:24:30 -06:00
22279a641a start of testing! 2025-03-07 16:11:15 -06:00
b37359a4f3 add tasty packages 2025-03-07 15:24:14 -06:00
c76d33f291 prepare for QuickCheck 2025-03-07 15:23:10 -06:00
b0c3a7626e see if this will fix tmux 2025-03-07 14:04:41 -06:00
d7b608bbeb updated lock file 2025-03-07 13:33:27 -06:00
ed7e0938a2 how to run instructions 2025-03-07 13:14:17 -06:00
c68ff2d329 fix warning 2025-03-07 13:11:36 -06:00
aca190ec0f simplification been done for a bit 2025-03-07 01:56:53 -06:00
7abac5e995 special int and float instructions 2025-03-07 01:14:12 -06:00
adff19b765 fix warnings 2025-03-07 01:14:00 -06:00
3cae011dfe more todo 2025-03-07 01:13:30 -06:00
164286d59a generic vector float instructions 2025-03-07 00:45:34 -06:00
67ed23d9ca genericize int mean 2025-03-07 00:45:17 -06:00
b74b43a9c0 added int lin alg functions 2025-03-06 23:55:20 -06:00
e373d9499d start of vector instructions 2025-03-06 19:51:23 -06:00
a9aba70bc4 add tasty 2025-03-06 16:23:39 -06:00
d59812b0fb start on moving lin alg functions over 2025-03-06 14:32:10 -06:00
0d590bd259 add hmatrix 2025-03-06 14:09:47 -06:00
7e19618c84 add library requirement 2025-03-06 14:09:06 -06:00
d69071cf47 knock off todo 2025-03-06 14:08:48 -06:00
2d7873d72c remove debugging/formatting 2025-03-06 03:07:20 -06:00
72c339e8b0 simplification added 2025-03-06 00:14:03 -06:00
c46c53616f simplification done 2025-03-05 23:08:26 -06:00
bac7751a83 start of simplification 2025-03-05 00:55:18 -06:00
d1d36eb3aa variation done 2025-03-04 16:11:37 -06:00
b002d571a3 more variation done 2025-03-04 14:17:07 -06:00
2b4d8896ea small TODO done 2025-03-04 14:16:44 -06:00
39f6b9cc53 work on variation 2025-03-03 14:34:30 -06:00
33b6f87a22 add balanced closed option 2025-03-03 14:33:18 -06:00
6db42c44fe selectionCases in all lexicase types 2025-03-02 22:08:22 -06:00
134b3476d2 finish up adding selection methods 2025-03-02 21:40:13 -06:00
5f6df518e6 add dsp library 2025-03-02 21:39:54 -06:00
3815130d09 almost done with lexicase 2025-03-02 01:56:50 -06:00
500fbb5d77 add new files 2025-03-01 23:22:39 -06:00
0dd02d06b3 updates here too 2025-03-01 23:22:31 -06:00
4b611a9d74 starting some testing 2025-03-01 23:22:07 -06:00
1293e27b69 selection and individual, remove cyclic dependencies for PushArgs 2025-03-01 23:21:43 -06:00
5a410dd605 more TODO done 2025-03-01 23:20:59 -06:00
9706a77ba9 downsample loose ends 2025-03-01 17:36:55 -06:00
70fd714340 bestIndPassesDownsample done 2025-03-01 16:31:20 -06:00
29617dd604 cleanup testing code 2025-03-01 16:30:40 -06:00
4342803211 add a period to the first sentence 2025-03-01 16:28:52 -06:00
27b29f8449 formatting 2025-03-01 16:23:19 -06:00
690b4507b2 remove unneeded comments 2025-03-01 16:21:00 -06:00
9c23017976 downsample done, need to test it now 2025-03-01 16:20:09 -06:00
92e5443ce5 redo README 2025-03-01 16:19:43 -06:00
d51a20f66f more downsample progress, only a few more functions to go :), need to test this 2025-03-01 04:21:10 -06:00
fc2aaff280 more of the downsample file translated :) 2025-03-01 00:34:31 -06:00
09b4c57784 more progress on downsampling 2025-02-28 02:59:00 -06:00
897f9bfb4a fix typo/add updateAtIndices 2025-02-27 23:25:53 -06:00
720c8296d2 progress on getDistancesBetweenCases 2025-02-27 22:37:45 -06:00
5f8f0db1c6 downsample maxmins done 2025-02-27 20:55:00 -06:00
4aa8aa9f2a part of the maxmin loop done 2025-02-27 02:52:19 -06:00
8e40396828 downsample maxmin pre-loop is done 2025-02-27 00:17:50 -06:00
33564d9b0c documentation for maxmin downsample 2025-02-27 00:01:38 -06:00
1c6421f6da downsample-maxmin start 2025-02-26 23:45:47 -06:00
06b4adb239 many changes 2025-02-26 20:50:27 -06:00
0c0d57dd8d convert loop to use PushData 2025-02-26 14:26:32 -06:00
76493bc362 middle of converting to PushData 2025-02-26 03:46:59 -06:00
058bbbfd94 fix conflict 2025-02-26 03:00:44 -06:00
4b10281941 add PushData 2025-02-26 02:58:57 -06:00
5383356791 fix count discrepancy, thx Dr. Spector :) 2025-02-25 23:32:34 -06:00
db497a087c proper indexing 2025-02-25 22:20:52 -06:00
2d9840c51b skeleton done 2025-02-25 18:53:52 -06:00
5012cb2ce1 GP skeleton almost done 2025-02-25 18:48:05 -06:00
2f6675e9f5 add downsample 2025-02-25 18:47:50 -06:00
53c490b3b3 mission failed 2025-02-25 15:23:01 -06:00
4f888f44ae mkFlakeNoCC doesn't exist lol 2025-02-25 15:20:53 -06:00
5a070bf295 attempt to add a shellHook 2025-02-25 15:10:39 -06:00
70e4fa6ab6 try with NoCC to fix tmux artifacting 2025-02-25 15:03:53 -06:00
dec879498f more gpLoop' progress 2025-02-25 14:59:34 -06:00
747bf57d03 add variation file 2025-02-25 14:59:23 -06:00
52ed502b61 balance close mention 2025-02-25 14:59:04 -06:00
0c1d2a5d50 Nix mention 2025-02-25 14:28:18 -06:00
6e9b9a4827 ormolu and threadscope 2025-02-25 14:17:29 -06:00
538178ccfa start of [individual] 2025-02-25 14:15:15 -06:00
164765aa23 comment out base gpLoop' 2025-02-25 14:02:39 -06:00
6ca07694e6 change to HushGP.cabal 2025-02-25 03:14:03 -06:00
5e86915bd1 try ghc982 2025-02-25 01:44:21 -06:00
c7d0927b3f comment out project root stuff 2025-02-25 01:36:09 -06:00
158172a6ae uncomment a config line 2025-02-25 01:34:49 -06:00
780e23e93b add flake.log 2025-02-25 01:32:12 -06:00
208a73aae5 add flake 2025-02-25 01:30:59 -06:00
b57a802f11 more gp loop/formatting 2025-02-21 00:50:10 -06:00
0ebfb13e04 less IO functions, pre-loop done, next is the main loop 2025-02-20 01:49:38 -06:00
4fbd42f9ff fix yank dup bug 2025-02-20 01:49:04 -06:00
56551924ae remove old branch leftovers 2025-02-18 00:20:21 -06:00
56a5e898dc Merge pull request 'vectors_code into main' (#2) from vectors_code into main
Reviewed-on: http://c57keqcdj43nn2xukakrqm2wwx255et7oyuktopk5fpopzzg54thkjid.onion/evo-trading/HushGP/pulls/2
2025-02-18 00:17:53 -06:00
88b5b52813 parallelism/start the individual creation 2025-02-17 22:54:41 -06:00
090a402f06 finish int regression framework, time for the rest of pieces 2025-02-15 23:46:40 -06:00
b88a4944f9 int regression start 2025-02-15 01:24:40 -06:00
feddc3cbfe add push arguments, more fun to come 2025-02-14 20:02:38 -06:00
054d321102 comment out/remove debugging code 2025-02-14 17:00:13 -06:00
153f4264e2 fix block issue, gonna run a few more tests 2025-02-14 16:32:23 -06:00
b7926662e1 fix skip not working 2025-02-14 01:20:54 -06:00
2399b7660b this stuff is broken rn. It's bed time 2025-02-14 01:11:37 -06:00
eab4932d54 I love plushy genomes 2025-02-14 00:47:04 -06:00
46fe4fac0f plushy -> push done 2025-02-14 00:46:48 -06:00
ed960acef3 formatting 2025-02-13 23:34:00 -06:00
915ec947f5 a lot of changes, Int -> Integer, Float -> Double, ERCs, plushy testing, ... 2025-02-13 23:18:04 -06:00
5e08620a50 ercs on todo 2025-02-13 16:36:31 -06:00
56d546d1fd supersize the plushy work 2025-02-13 02:44:32 -06:00
c8474bd4ef more plushy todo 2025-02-13 02:42:24 -06:00
714485e2e0 add plushy todo 2025-02-13 02:40:40 -06:00
480f600ad3 add commutative opposites where it applies 2025-02-13 00:39:52 -06:00
24398989be make some tests runnable 2025-02-13 00:38:21 -06:00
108bc14d62 more todo 2025-02-13 00:37:58 -06:00
437c99c946 TEMPLATE HASKELL git statusgit statusgit statusgit status 2025-02-13 00:06:07 -06:00
84e5c7b1df update instructions list/formatting 2025-02-11 17:05:16 -06:00
899aaa93a7 strikethrough template haskell 2025-02-11 16:37:31 -06:00
14f00420da oops 2025-02-11 16:31:31 -06:00
0dcc8b6b85 remove template haskell file 2025-02-11 16:30:55 -06:00
2f2b19e3d0 gonna abandon TH 2025-02-11 16:30:15 -06:00
cff71ac4ca make todo a bit more concise 2025-02-11 13:02:24 -06:00
68e1ebf268 more todo 2025-02-11 13:01:42 -06:00
76df52c554 Start to play around with TH :) 2025-02-11 00:13:34 -06:00
1155905be3 move moveable utility functions to utility file 2025-02-10 23:39:52 -06:00
7d6d8bf23d vector functions done, all documented 2025-02-10 23:17:59 -06:00
3dce0daf4e docs written for vector bools 2025-02-10 22:47:06 -06:00
a4c04711b2 vectorBool docs/add generic vector instructions 2025-02-10 16:58:40 -06:00
7bb825991c fix docs/more string functions 2025-02-10 16:10:53 -06:00
14ec3b727e most string funcs generic/doced 2025-02-10 14:44:12 -06:00
058b019ccd modify maintainer status 2025-02-10 14:43:29 -06:00
b936dda857 more documentation/generic string functions 2025-02-09 22:17:18 -06:00
6e40f3d3c2 template haskell to generate function lists 2025-02-09 22:12:32 -06:00
2d6b888e2e generic string instructions and more documentation 2025-02-09 19:34:23 -06:00
91bd09c00f more TODO 2025-02-09 19:33:58 -06:00
efb4d80962 float docs, typo fixes, string -> float fix 2025-02-09 14:27:45 -06:00
6a78fd0ba6 Generic documentation done 2025-02-09 14:00:50 -06:00
c4417cf22f GP todo 2025-02-09 14:00:34 -06:00
ebaf1dfc20 more documentation, more to go 2025-02-08 20:57:24 -06:00
de18d828a9 documentation, time to fix my sleep schedule 2025-02-07 17:55:12 -06:00
9a3453ad5f more todo 2025-02-07 17:53:16 -06:00
ac8d1974f2 remove lens note 2025-02-07 17:53:01 -06:00
867f3ac440 make pattern matching parameters consistent 2025-02-07 15:51:24 -06:00
ff31a8fa35 move the state parameter to final position in all functions 2025-02-07 15:21:17 -06:00
0b280af591 disambiguate isEmpty and isStackEmpty 2025-02-07 14:46:18 -06:00
ad4b7a2341 more instructions/knocking off the TODO 2025-02-07 01:03:14 -06:00
b47371a2fd more changes/todo 2025-02-06 23:42:15 -06:00
813b4db541 moved 2025-02-06 18:37:09 -06:00
7c7de9f3e8 restructuring/logical -> bool 2025-02-06 16:52:42 -06:00
2404e7e5e1 instruction list, comment cleanup, todos 2025-02-06 15:49:06 -06:00
194c025486 the start to implementing plushy interpretation 2025-02-05 23:46:37 -06:00
add949ed05 modify Eq function 2025-02-05 01:05:51 -06:00
e40ef0ce62 more tests and many more togo 2025-02-05 01:03:24 -06:00
58cb593cff more gp notes 2025-02-04 14:43:08 -06:00
12b8cb56a7 formatting and generic tests 2025-02-04 03:36:33 -06:00
83066eb74c start work on using quickcheck to test states 2025-02-02 22:27:46 -06:00
153e560801 remove generic reference 2025-02-01 22:34:31 -06:00
8c95f3ac06 remove LearnQuickCheck 2025-02-01 20:46:04 -06:00
2d70f666e8 delete MainOld 2025-02-01 18:19:07 -06:00
413b9eee44 only keep things I like from learn_quickcheck 2025-02-01 18:15:09 -06:00
319f682d4a clean up/basic tests 2025-02-01 01:24:27 -06:00
27ee85ae28 string name in StateFunc 2025-02-01 01:24:07 -06:00
8fa26fbf27 adjust for name in StateFunc 2025-02-01 01:23:45 -06:00
24442169bf also formatting 2025-02-01 00:18:33 -06:00
32b48b79d0 formatting 2025-02-01 00:18:17 -06:00
e5285e5c8f quickcheck class implementations done 2025-01-31 23:50:07 -06:00
125f137643 trying things... 2025-01-31 18:43:15 -06:00
b3e1b96ff5 move/rename 2025-01-31 18:35:39 -06:00
f484da2308 more quickcheck learning, just gonna go for it now 2025-01-31 18:34:31 -06:00
6c4c84e7dc Merge branch 'vectors_code' into learn_quickcheck
merge vectors_code into learn_quickcheck
2025-01-31 17:12:39 -06:00
dc9e9fdb19 calculus -> all propeller instructions 2025-01-31 15:52:53 -06:00
1d56143712 comment cleanup 2025-01-31 15:49:06 -06:00
8d01d9a208 burned out of quick check for today, more later 2025-01-30 20:59:36 -06:00
63 changed files with 6764 additions and 2522 deletions

View File

@ -19,39 +19,61 @@ version: 0.1.0.0
synopsis: A PushGP implementation in Haskell.
-- The package author(s).
author: Taylor
author: Rowan Torbitzky-Lane, Taylor
-- An email address to which users can send suggestions, bug reports, and patches.
maintainer: behindthebrain@zoho.eu
maintainer: rowan.a.tl@protonmail.com
category: Data
build-type: Simple
common warnings
ghc-options: -Wall
ghc-options: -Wall -XTemplateHaskell -threaded
library
-- Import common warning flags.
import: warnings
-- Modules exported by the library.
exposed-modules: Push
, GP
, State
, Instructions
, Instructions.IntInstructions
, Instructions.ExecInstructions
, Instructions.FloatInstructions
, Instructions.GenericInstructions
, Instructions.LogicalInstructions
, Instructions.CodeInstructions
, Instructions.StringInstructions
, Instructions.CharInstructions
, Instructions.VectorIntInstructions
, Instructions.VectorFloatInstructions
, Instructions.VectorStringInstructions
, Instructions.VectorLogicalInstructions
, Instructions.VectorCharInstructions
exposed-modules: HushGP.Push
, HushGP.TH
, HushGP.Utility
, HushGP.Genome
, HushGP.State
, HushGP.Instructions
, HushGP.Instructions.IntInstructions
, HushGP.Instructions.ExecInstructions
, HushGP.Instructions.FloatInstructions
, HushGP.Instructions.GenericInstructions
, HushGP.Instructions.BoolInstructions
, HushGP.Instructions.CodeInstructions
, HushGP.Instructions.StringInstructions
, HushGP.Instructions.CharInstructions
, HushGP.Instructions.VectorIntInstructions
, HushGP.Instructions.VectorFloatInstructions
, HushGP.Instructions.VectorStringInstructions
, HushGP.Instructions.VectorBoolInstructions
, HushGP.Instructions.VectorCharInstructions
, HushGP.Instructions.Utility
, HushGP.Instructions.Opens
, HushGP.PushTests
, HushGP.PushTests.IntTests
, HushGP.PushTests.VectorIntTests
, HushGP.PushTests.GenericTests
, HushGP.PushTests.UtilTests
, HushGP.PushTests.TestStates
, HushGP.PushTests.GP.Selection
, HushGP.GP
, HushGP.GP.PushArgs
, HushGP.GP.Variation
, HushGP.GP.Downsample
, HushGP.GP.PushData
, HushGP.GP.Selection
, HushGP.GP.Individual
, HushGP.GP.Simplification
, HushGP.Problems.IntegerRegression
, HushGP.Tools.Metrics
-- Modules included in this library but not exported.
-- other-modules:
@ -61,7 +83,7 @@ library
-- Other library packages from which modules are imported.
build-depends:
base, containers, lens, split
base, containers, lens, split, regex-tdfa, template-haskell, random >= 1.3.0, parallel, dsp, hmatrix, tasty, tasty-hunit
-- Directories containing source files.
hs-source-dirs: src
@ -118,4 +140,35 @@ test-suite HushGP-test
-- Test dependencies.
build-depends:
base,
HushGP
HushGP,
lens,
QuickCheck
test-suite HushGP-test-old
-- Import common warning flags.
import: warnings
-- Base language which the package is written in.
default-language: GHC2021
-- Modules included in this executable, other than Main.
-- other-modules:
-- LANGUAGE extensions used by modules in this package.
-- other-extensions:
-- The interface type and version of the test suite.
type: exitcode-stdio-1.0
-- Directories containing source files.
hs-source-dirs: test
-- The entrypoint to the test suite.
main-is: MainOld.hs
-- Test dependencies.
build-depends:
base,
HushGP,
lens,

View File

@ -15,7 +15,7 @@ test: # Runs unit tests.
runghc -i./src/ test/Main.hs
format: # Formats code using ormolu.
ormolu --mode inplace app/*.hs src/*.hs test/*.hs
ormolu --mode inplace app/*.hs src/HushGP/*.hs test/*.hs
hlint: # HLint for lint suggestions.
hlint src/*.hs

View File

@ -1,62 +1,39 @@
# HushGP
A PushGP implementation in Haskell
A PushGP implementation in Haskell.
This branch is meant to to go one by one and finish implementing all of
the functions in the pyshgp list.
Note: **This is an imcomplete library at this time. I am still developing it.**
https://erp12.github.io/pyshgp/html/core_instructions.html
## Overview
# Big Problem
I am developing this library using:
- GHC 9.8.2
- Cabal 3.12.1.0
There is no easy way to determine equality of two functions in Haskell. No comparing names, no nothing.
We coult compare applying two functions to an example state, but that would get tedious and costly quickly.
## How to run
The only idea floating in my head at the moment is to attach a string to the `StateFunc` Gene to
track what the functions are. This would require a painful redefinition of the tests, but I think would be
worth it in the grand scheme. Would mean we could also track the functions when outputting them after training.
In order to run this library. There is some manual configuration needed. For an example, check
out `src/HushGP/Problems/IntegerRegression.hs`. This contains the parts needed for a full evolutionary run.
## Tasks
* [ ] Post minimal core of exec to haskell discourse for advice about speed optimization.
* [x] Do test-driven development on this one.
* [x] Write tests for every function.
* [x] tests/ are just copied from make-grade, need to write for this project.
* [ ] Included examples of basic assertions, QuickCheck, Hspec, hspec-quickcheck.
* [x] Look at Lenses library for abstraction
The user is expected to provide their own data, their own fitness function, and the set of instructions
they would like to use. This set can be found in the files of `src/HushGP/Instructions`. You can also
check the haddock documentation for lists of these as well.
## Design considerations
The biggest design constraint is that for the exec stack (but not data stacks)
we have to be able to detect type at runtime.
The best way to run this library is to use cabal. `cabal repl` for development. TODO: Command for
fully compiling and building an executable to run.
A simple way to do this for the exec stack is as a list of custom data type.
That custom Gene data type must have as many sub-types as there are types + fuction types.
# Building Instructions
If the input stack is singular, then it needs a general Gene data type,
but if there was an input stack per type, they could be specific.
In order to build Hush with hmatrix, `lapack` development libraries must be installed on your
system.
I would really like to benchmark some of the following three versions for speed:
dnf: `sudo apt install lapack-devel`
1) Where some functions can act on all stacks (this repo),
and thus every data stack is a list of a more general Gene type,
elements of which are wrapped in data TypeGene so they can be identified in stack-general functions.
To bind all the stacks for convenience,
we could put each stack list in a tuple, or a custom data type, Data.Map or Data.HashMap.
The exec stack will always need a more general Gene type,
with Gene types wrapping each individual thing, for runtime identification.
Nix doesn't have this problem.
2) Where type-specific functions act on each stack independently,
and thus each data stack can have exclusive specific basic types,
which are not wrapped in data TypeGene, because they do not need to be identified.
To bind all the stacks for convenience,
we could put each stack list in a tuple, or a custom data type,
but not in a or Data.Map or Data.HashMap, as those require homogenous (K, V) pairs.
The exec stack will always need a more general Gene type,
with Gene types wrapping each individual thing, for runtime identification.
## Nix Users
3) Alternatively, for the exec stack, we could store strings,
and eval strings (similar to my custumized version of propel clojure)
Regular and input stacks can stil be either TypeGene or basic types.
This is clearly not ideal.
This took my machine about 2 hours to build the environment after running `nix develop`.
4) For the exec stack itself,
typeable, data generic, ghc.generic, data.dynamic, heterogeneous lists, etc. could also help,
to detect the type of variables at runtime, but I would rather stick to language basics at first.
## Credits
Thanks to @mdominicis for the linear algebra functions!

47
TODO.md
View File

@ -2,11 +2,46 @@
## Push Language TODO
- [ ] Make all vector functions applicable to string functions and vice versa
- [ ] Implement Calculus functions as seen in propeller
- [ ] Implement Linear Algebra functions as specified in the previous papers
- [ ] Add a function to sort a vector
- [x] Make int yank, shove, yankdup, and shovedup generic
- [X] Make all vector functions applicable to string functions and vice versa
- [X] Implement all functions as seen in propeller
- [X] Implement all functions as seen in the specification
- [X] Implement Linear Algebra functions as specified in the previous papers
- [X] These are in a separate branch, just need merging now
- [X] Add a function to sort a vector forward and backwards
- [X] Disambiguate isEmpty and stackIsEmpty
- [X] Rename Logical to Bool
- [X] Make int yank, shove, yankdup, and shovedup generic
- [X] Write haddock documentation for each function
- [X] Refactor all functions to take state as the final parameter
- [X] Standardize the pattern matching parameter names, such as c1 : cs
- [ ] Write unit/quickcheck tests for the generic functions
- [X] Use template haskell to generate function lists
- [X] Move utility functions to their own file
- [ ] Make add/sub/mult/div/mod instructions generic
- [ ] Use template haskell to (mostly) generate functions from generic ones (Split files based on the arity of their functions)
- [X] Add more special functions like sqrt, pow
## PushGP TODO
- [ ] Implement a Plushy genome translator
- [X] Implement a Plushy genome translator
- [X] Implement ~~silent and~~ skip marker(s) as well
~~[ ] Have close amt of 1,2, and 3~~
- [X] Need a random genome generator
- I'm only going to implement propeller's :specified version
- Is the best according to the papers
- [X] Need a NoOp that opens blocks
- [ ] Have a way to balance amount of closes with open blocks
- Implement "balanced" closed PushArg
- [ ] Need to make genomes serializable (Check pysh json files)
- [ ] Add Memory
- [ ] Add history stack(s), like a call stack
- [ ] Implement interpreter options (PushArgs would work well)
- Should probably place this in a separate file
- [ ] Implement Novelty Lexicase selection
- [X] Implement different forms of downsampling
- [ ] Implement concurrent execution of creating random plushies and evaluating individuals
- [X] Devise a good way to implement ERCs
- [X] Implement random simplification of genomes
- [ ] Find a way to multi-thread this
- [ ] Look at using `uniformShuffleList` over System.Random.Shuffle
- [X] Impelment selectionCases for lexicase and tournament selection.
- [X] Make all randomness a float and not an int in Variation

77
flake.lock generated Normal file
View File

@ -0,0 +1,77 @@
{
"nodes": {
"flake-parts": {
"inputs": {
"nixpkgs-lib": "nixpkgs-lib"
},
"locked": {
"lastModified": 1741352980,
"narHash": "sha256-+u2UunDA4Cl5Fci3m7S643HzKmIDAe+fiXrLqYsR2fs=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "f4330d22f1c5d2ba72d3d22df5597d123fdb60a9",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "flake-parts",
"type": "github"
}
},
"haskell-flake": {
"locked": {
"lastModified": 1741200839,
"narHash": "sha256-45psZ9Xd+50w9KrZmg1y5yH7MTm0J5pKWGD7GcRdPm0=",
"owner": "srid",
"repo": "haskell-flake",
"rev": "b6508f818abb14a4df436378ff24e3e3afc9cbd0",
"type": "github"
},
"original": {
"owner": "srid",
"repo": "haskell-flake",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1741310760,
"narHash": "sha256-aizILFrPgq/W53Jw8i0a1h1GZAAKtlYOrG/A5r46gVM=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "de0fe301211c267807afd11b12613f5511ff7433",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-lib": {
"locked": {
"lastModified": 1740877520,
"narHash": "sha256-oiwv/ZK/2FhGxrCkQkB83i7GnWXPPLzoqFHpDD3uYpk=",
"owner": "nix-community",
"repo": "nixpkgs.lib",
"rev": "147dee35aab2193b174e4c0868bd80ead5ce755c",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "nixpkgs.lib",
"type": "github"
}
},
"root": {
"inputs": {
"flake-parts": "flake-parts",
"haskell-flake": "haskell-flake",
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

69
flake.nix Normal file
View File

@ -0,0 +1,69 @@
# https://community.flake.parts/haskell-flake/dependency
{
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
flake-parts.url = "github:hercules-ci/flake-parts";
haskell-flake.url = "github:srid/haskell-flake";
};
outputs = inputs@{ self, nixpkgs, flake-parts, ... }:
flake-parts.lib.mkFlake { inherit inputs; } {
systems = nixpkgs.lib.systems.flakeExposed;
imports = [ inputs.haskell-flake.flakeModule ];
perSystem = { self', pkgs, lib, ... }: {
# Typically, you just want a single project named "default". But
# multiple projects are also possible, each using different GHC version.
haskellProjects.default = {
# The base package set representing a specific GHC version.
# By default, this is pkgs.haskellPackages.
# You may also create your own. See https://community.flake.parts/haskell-flake/package-set
basePackages = pkgs.haskell.packages.ghc982;
# Extra package information. See https://community.flake.parts/haskell-flake/dependency
#
# Note that local packages are automatically included in `packages`
# (defined by `defaults.packages` option).
#
projectRoot = builtins.toString (lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
./src
./HushGP.cabal
];
});
packages = {
# aeson.source = "1.5.0.0"; # Override aeson to a custom version from Hackage
# shower.source = inputs.shower; # Override shower to a custom source path
};
settings = {
# aeson = {
# check = false;
# };
# relude = {
# haddock = false;
# broken = false;
# };
};
devShell = {
mkShellArgs = {
shellHook = ''
export SHELL=${pkgs.lib.getExe pkgs.bashInteractive}
'';
};
# Programs you want to make available in the shell.
# Default programs can be disabled by setting to 'null'
tools = hp: { ormolu = hp.ormolu; threadscope = hp.threadscope; };
# Check that haskell-language-server works
# hlsCheck.enable = true; # Requires sandbox to be disabled
};
};
# haskell-flake doesn't set the default package, but you can do it here.
packages.default = self'.packages.HushGP;
};
};
}

View File

@ -1,3 +0,0 @@
module GP where
-- import Debug.Trace (trace, traceStack)

120
src/HushGP/GP.hs Normal file
View File

@ -0,0 +1,120 @@
-- | The main file containing information about the GP loop and various population transformation functions.
module HushGP.GP where
import Control.Monad
import Control.Parallel.Strategies
import Data.List (sort, uncons)
import HushGP.GP.Downsample
import HushGP.GP.Individual
import HushGP.GP.PushArgs
import HushGP.GP.PushData
import HushGP.GP.Selection
import HushGP.GP.Simplification
import HushGP.GP.Variation
import HushGP.Genome
import System.Random
-- import Debug.Trace (trace, traceStack)
-- | Using a PushArgs object, generates a population of the specified size with the
-- specified instructions in parallel.
generatePopulation :: PushArgs -> IO [Individual]
generatePopulation pushArgs@(PushArgs {populationSize = popSize}) = do
pop <- replicateM popSize (makeRandomIndividual pushArgs)
return (pop `using` evalList rpar) -- Does this work? Need to test this with the HEC viewing tool.
-- | Evaluates a population of plushies with the error function passed in via PushArgs and sorts them.
-- TODO: Need to make this runnable in parallel too.
evaluatePopulation :: PushArgs -> [PushData] -> [Individual] -> [Individual]
evaluatePopulation pushArgs passedTrainingData population = sort $ zipWith updateIndividual (map (errorFunction pushArgs pushArgs passedTrainingData . plushy) population) population
-- | A helper function used in evaluatePopulation. Takes a [Double] as the error scores and an individual.
-- Updates the error fields in an individual, and returns it.
updateIndividual :: [Double] -> Individual -> Individual
updateIndividual errors ind = ind {totalFitness = Just (sum errors), fitnessCases = Just errors}
-- | The start of the gp loop. Generates the population and then calls
-- gpLoop' with modifications to the variables if needed.
gpLoop :: PushArgs -> IO ()
gpLoop pushArgs@(PushArgs {trainingData = tData}) = do
unEvaledPopulation <- generatePopulation pushArgs
let indexedTrainingData = assignIndicesToData tData
gpLoop' pushArgs 0 0 unEvaledPopulation indexedTrainingData
-- | The guts of the GP loop. Where the work gets done after the initialization happens
-- in the main gpLoop function. The first Int holds the generation count. The second Int
-- holds the evaluation count. The list of Individuals is the population. The last parameter is
-- the training data (possibly downsampled).
gpLoop' :: PushArgs -> Int -> Int -> [Individual] -> [PushData] -> IO ()
gpLoop'
pushArgs@(PushArgs {enableDownsampling = enableDS, solutionErrorThreshold = seThresh, downsampleParentsGens = dsParentGens, downsampleParentRate = dsParentRate, trainingData = trData, elitism = isElite, populationSize = popSize, useSimplification = useSimp, errorFunction = errorFunc, maxGenerations = maxGens, testingData = teData})
generation
evaluations
population
indexedTrainingData = do
when bestIndPassesDownsample $ print $ "Semi Success Generation: " <> show generation
parentReps <- do
shuffledParents <- fst . uniformShuffleList population <$> initStdGen
if enableDS && (generation `mod` dsParentGens == 0)
then pure $ take (floor @Float (dsParentRate * (fromIntegral @Int @Float $ length population))) shuffledParents
else pure []
let nextAction
| ( bestIndPassesDownsample
&& ( (case totalFitness (updateIndividual (errorFunc epsilonPushArgs indexedTrainingData (plushy bestInd)) bestInd) of (Just x) -> x; _ -> error "Error: Best downsample individual has no fitness!")
<= solutionErrorThreshold epsilonPushArgs
)
)
|| (not enableDS && ((case totalFitness bestInd of (Just x) -> x; _ -> error "error: Best non-downsample individual has no fitness!") <= seThresh)) =
do
print $ "Successful generation: " <> show generation
print $ "Successful plushy: " <> show (plushy bestInd)
print $ "Successful program: " <> show (plushyToPush pushArgs (plushy bestInd))
print $ "Total test error: " <> show (errorFunc epsilonPushArgs teData (plushy bestInd))
when useSimp $
do
simplifiedPlushy <- autoSimplifyPlushy pushArgs (plushy bestInd)
print $ "Simplified plushy: " <> show simplifiedPlushy
print $ "Simplified program: " <> show (plushyToPush pushArgs simplifiedPlushy)
print $ "Total simplified test error: " <> show (errorFunc epsilonPushArgs teData simplifiedPlushy)
| (not enableDS && (generation >= maxGens))
|| (enableDS && (evaluations >= (maxGens * length population * length indexedTrainingData))) = do
print $ "Max gens: " <> show maxGens
print $ "Best individual: " <> show (plushy bestInd)
| otherwise = do
newPop <- if isElite then replicateM (popSize - 1) (newIndividual epsilonPushArgs evaledPop) else replicateM popSize (newIndividual epsilonPushArgs evaledPop)
gpLoop'
pushArgs
(succ generation)
( evaluations
+ (populationSize pushArgs * length (trainingData pushArgs))
+ (if generation `mod` downsampleParentsGens pushArgs == 0 then length parentReps * (length indexedTrainingData - length (trainingData pushArgs)) else 0)
+ (if bestIndPassesDownsample then length indexedTrainingData - length trData else 0)
)
( if isElite
then bestInd : newPop
else newPop
)
( if enableDS && ((generation `mod` dsParentGens) == 0)
then updateCaseDistances repEvaluatedPop indexedTrainingData indexedTrainingData (informedDownsamplingType pushArgs) (seThresh / fromIntegral @Int @Double (length indexedTrainingData))
else indexedTrainingData
)
print ("Generation: " <> show generation)
print ("Len Population: " <> show (length population))
print ("Best Ind: " <> show (plushy bestInd) <> " : " <> show (totalFitness bestInd))
print "----------------------------------------------"
nextAction
where
-- \| This will have downsampling functionality added later.
repEvaluatedPop :: [Individual]
repEvaluatedPop =
if enableDS
then evaluatePopulation pushArgs indexedTrainingData population
else []
evaledPop :: [Individual]
evaledPop = evaluatePopulation pushArgs trData population
bestInd :: Individual
bestInd = case uncons evaledPop of Just (x, _) -> x; _ -> error "Error: Population is empty!"
bestIndPassesDownsample :: Bool
bestIndPassesDownsample = enableDS && (extractTotalFitness bestInd <= seThresh)
epsilonPushArgs :: PushArgs
epsilonPushArgs = pushArgs {epsilons = Just $ epsilonList evaledPop}

152
src/HushGP/GP/Downsample.hs Normal file
View File

@ -0,0 +1,152 @@
module HushGP.GP.Downsample where
import System.Random
import Data.List
import Data.Maybe
import HushGP.Utility
import HushGP.GP.PushData
import HushGP.GP.PushArgs
import HushGP.Tools.Metrics
import HushGP.Instructions.Utility
import HushGP.GP.Individual
-- |Sets the index of the passed training data.
assignIndicesToData :: [PushData] -> [PushData]
assignIndicesToData oldData = zipWith (\dat idx -> dat{_downsampleIndex = Just idx}) oldData [0..]
-- |Initializes cases distances for passed training data.
initializeCaseDistances :: PushArgs -> [PushData]
initializeCaseDistances (PushArgs {trainingData = tData, populationSize = popSize}) = [ dat{_caseDistances = Just (replicate (length tData) (fromIntegral @Int @Double popSize))} | dat <- tData ]
-- |Draws a random amount of data points from a passed list of data points.
selectDownsampleRandom :: PushArgs -> [PushData] -> IO [PushData]
selectDownsampleRandom (PushArgs {downsampleRate = dsRate}) pushData = take (floor (dsRate * fromIntegral @Int @Float (length pushData))) . fst . uniformShuffleList pushData <$> initStdGen
-- |Selects a downsample that has it's cases maximally far away by sequentially
-- adding cases to the downsample that have their closest case maximally far away.
selectDownsampleMaxmin :: PushArgs -> [PushData] -> IO [PushData]
selectDownsampleMaxmin (PushArgs {downsampleRate = dsRate}) pushData = do
shuffledCases <- fst . uniformShuffleList pushData <$> initStdGen
let goalSize = floor @Float @Int (dsRate * (fromIntegral @Int @Float $ length pushData))
selectDownsampleMaxmin'
(case uncons shuffledCases of (Just (x, _)) -> [x]; _ -> error "error: shuffledCases empty!")
(drop 1 shuffledCases)
goalSize
-- |The main loop of selectDownsampleMaxmin. This is where most of calculation happens.
-- When called from selectDownsampleMaxmin: The first [PushData] holds the head of the
-- original pushData wrapped in a list, the second [PushData] holds the rest of the list
-- without the aformentioned head. The Int is the goal size derived from the downsample rate
-- and the length of the original [pushData].
selectDownsampleMaxmin' :: [PushData] -> [PushData] -> Int -> IO [PushData]
selectDownsampleMaxmin' newDownsample casesToPickFrom goalSize
| length newDownsample >= goalSize = pure newDownsample
| otherwise = do
let newDistances = map extractDistance newDownsample
let minCaseDistances = minOfColumns (map (\distList -> filterByIndex distList (map extractIndex casesToPickFrom)) newDistances)
selectedCaseIndex <- argMax minCaseDistances
stdGen <- initStdGen
selectDownsampleMaxmin'
((casesToPickFrom !! selectedCaseIndex) : newDownsample)
(fst $ uniformShuffleList (deleteAt selectedCaseIndex casesToPickFrom) stdGen)
goalSize
-- |selects a downsample that has it's cases maximally far away by sequentially
-- adding cases to the downsample that have their closest case maximally far away
-- automatically stops when the maximum minimum distance is below delta
selectDownsampleMaxminAdaptive :: PushArgs -> [PushData] -> IO [PushData]
selectDownsampleMaxminAdaptive (PushArgs {caseDelta = cDelta}) pushData = do
shuffledCases <- fst . uniformShuffleList pushData <$> initStdGen
selectDownsampleMaxminAdaptive'
(case uncons shuffledCases of (Just (x, _)) -> [x]; _ -> error "error: shuffledCases empty!")
(drop 1 shuffledCases)
cDelta
-- |The main loop of selectDownsampleMaxmin. This is where most of calculation happens.
-- When called from selectDownsampleMaxmin: The first [PushData] holds the head of the
-- original pushData wrapped in a list, the second [PushData] holds the rest of the list
-- without the aformentioned head. The Int is the caseDelta derived from the downsample rate
-- and the length of the original [pushData].
selectDownsampleMaxminAdaptive' :: [PushData] -> [PushData] -> Double -> IO [PushData]
selectDownsampleMaxminAdaptive' newDownsample casesToPickFrom cDelta = do
let newDistances = map extractDistance newDownsample
let minCaseDistances = minOfColumns (map (\distList -> filterByIndex distList (map extractIndex casesToPickFrom)) newDistances)
selectedCaseIndex <- argMax minCaseDistances
stdGen <- initStdGen
if null casesToPickFrom || (maximum minCaseDistances <= cDelta)
then pure newDownsample
else selectDownsampleMaxminAdaptive'
((casesToPickFrom !! selectedCaseIndex) : newDownsample)
(fst $ uniformShuffleList (deleteAt selectedCaseIndex casesToPickFrom) stdGen)
cDelta
-- |Returns the distance between two cases given a list of individual error vectors, and the index these
-- cases exist in the error vector. Only makes the distinction between zero and nonzero errors.
getDistanceBetweenCases :: [[Double]] -> Int -> Int -> Double
getDistanceBetweenCases errorLists caseIndex0 caseIndex1 =
if lhe < caseIndex0 || lhe < caseIndex1 || caseIndex0 < 0 || caseIndex1 < 0
then fromIntegral @Int @Double $ length errorLists
else sum $ zipWith (\e0 e1 -> abs $ abs (signum e0) - abs (signum e1)) errors0 errors1
where
lhe :: Int -- length head errorLists
lhe = length $ case uncons errorLists of Just (x, _) -> x; _ -> error "Error: errorLists is empty!"
errors0 :: [Double]
errors0 = map (\e -> case e !? caseIndex0 of Just x -> x; _ -> 0) errorLists
errors1 :: [Double]
errors1 = map (\e -> case e !? caseIndex1 of Just x -> x; _ -> 0) errorLists
-- |Updates a list with the values from another list based on an index from a third list.
-- The first list (bigList) has its indices updated with the values from the second list (smallList)
-- per index notated in the third [Int] list.
updateAtIndices :: [a] -> [a] -> [Int] -> [a]
updateAtIndices bigList _ [] = bigList
updateAtIndices bigList smallList indices =
if length smallList /= length indices || any (\x -> x < 0 || x >= length bigList) indices
then bigList
else updateAtIndices' bigList smallList indices
-- |Look at updateAtIndicies for documentation. You should probably not
-- call this function. There is error checking in updateAtIndices, not this one.
updateAtIndices' :: [a] -> [a] -> [Int] -> [a]
updateAtIndices' bigList _ [] = bigList
updateAtIndices' bigList [] _ = bigList
updateAtIndices' bigList (sval:svals) (idx:idxs) = updateAtIndices' (replaceAt idx sval bigList) svals idxs
-- |Merges two lists of [Pushdata], replacing the PushData in the lists with their corresponding
-- (based on index) PushData in the small list.
mergePushDataListsAtIndex :: [PushData] -> [PushData] -> [PushData]
mergePushDataListsAtIndex bigList smallList = map (\x -> let correspondingSmall = find (\y -> extractIndex x == extractIndex y) smallList in fromMaybe x correspondingSmall) bigList
-- |Replaces all ints of a list that equal the minimum int in said same list with 0.
replaceMinsWithZero :: (Num a, Ord a) => [a] -> [a]
replaceMinsWithZero xs = map (\x -> if minimum xs == x then 0 else x) xs
-- |Replaces values within a delta of zero with zero, mainly used for regression problems.
replaceCloseZeroWithZero :: (Num a, Ord a) => a -> [a] -> [a]
replaceCloseZeroWithZero delta = map (\x -> if delta >= x then 0 else x)
-- |Converts a set of errors into a list where all the elite errors are replaced with 0s so that we can use
-- it in the selection of downsamples with elite/not-elite selection.
convertToEliteError :: forall a. (Num a, Ord a) => [[a]] -> [[a]]
convertToEliteError = map (replaceMinsWithZero @a) -- crazy lambda reduction. Is it worth it here?
-- |Converts a set of errors into a list where all of the errors are replaced with within a delta.
convertToSoftError :: forall a. (Num a, Ord a) => a -> [[a]] -> [[a]]
convertToSoftError delta = map (delta `replaceCloseZeroWithZero`)
-- |Updates the cases distances when downsampling.
updateCaseDistances :: [Individual] -> [PushData] -> [PushData] -> String -> Double -> [PushData]
updateCaseDistances evaledPop downsampleData trainData informedDownsamplingType solutionThreshold =
mergePushDataListsAtIndex trainData
(mapIndexed (\idx dCase -> dCase{_caseDistances = Just (updateAtIndices (extractDistance dCase)
(map (getDistanceBetweenCases corrErrors idx) [0..(length dsIndicies - 1)]) dsIndicies)}) downsampleData)
where
dsIndicies :: [Int]
dsIndicies = map extractIndex downsampleData
errors :: [[Double]]
errors = map extractFitnessCases evaledPop
corrErrors :: [[Double]]
corrErrors = case informedDownsamplingType of
"elite" -> convertToEliteError errors
"soft" -> convertToSoftError solutionThreshold errors
_ -> errors

View File

@ -0,0 +1,33 @@
module HushGP.GP.Individual where
import HushGP.State
-- | The structure for an individual containing the genome, the totalFitness, and
-- the individual fitness cases for lexicase.
data Individual = Individual
{ plushy :: [Gene],
totalFitness :: Maybe Double,
fitnessCases :: Maybe [Double],
selectionCases :: Maybe [Int]
}
deriving (Show, Eq)
instance Ord Individual where
ind0 <= ind1 = totalFitness ind0 <= totalFitness ind1
-- |Creates a new individual with all fields set to Nothing besides plushy which gets set to the
-- passed [Gene].
postVariationInd :: [Gene] -> Individual
postVariationInd newPlushy = Individual{plushy = newPlushy, totalFitness = Nothing, fitnessCases = Nothing, selectionCases = Nothing}
-- | Extracts the fitnessCases from an Individual. Errors if the field is empty.
-- Known as :errors in propeller.
extractFitnessCases :: Individual -> [Double]
extractFitnessCases Individual {fitnessCases = Nothing} = error "Error: fitnessCases is empty!"
extractFitnessCases Individual {fitnessCases = Just xs} = xs
-- | Extracts the total fitness from and Individual. Errors if the field is empty.
-- Known as :total-error in propeller.
extractTotalFitness :: Individual -> Double
extractTotalFitness Individual {totalFitness = Nothing} = error "Error: totalFitness is empty!"
extractTotalFitness Individual {totalFitness = Just x} = x

154
src/HushGP/GP/PushArgs.hs Normal file
View File

@ -0,0 +1,154 @@
module HushGP.GP.PushArgs where
import HushGP.State
import HushGP.Instructions
import HushGP.GP.PushData
-- | The structure holding the arguments for the various aspects
-- of the evolutionary run in Hush.
data PushArgs = PushArgs
{
-- | For alternation, std deviation for index when alternating.
alignmentDeviation :: Double,
-- | For alternation, probability of switching parents at each location. Should be a value in the range [1,100]
alternationRate :: Double,
-- | For bmx, rate genes are exchanged.
bmxExchangeRate :: Float,
-- | For bmx, max length of a gene.
bmxGeneLengthLimit :: Int,
-- | For bmx, mutation rate for gaps.
bmxGapChangeProbability :: Float,
-- | For bmx, whether mates selected using reverse case sequences of first parent
bmxIsComplementary :: Bool,
-- | For bmx, don't exchange distance if greater than this
bmxMaxDistance :: Int,
-- | For bmx, only allow exchanges between individual with same number of genes.
bmxSameGeneCount :: Bool,
-- | For bmx, swap segment with same sequence index, not by best match
ssxNotBmx :: Bool,
-- | Ways to construct a phenotype from a plushy genome, so far only "specified" is implemented. Unused (for now).
closes :: String,
-- | Whether or not to use best match crossover
useBMX :: Bool,
-- | Custom report for each generation if provided.
customReport :: Maybe (PushArgs -> IO ()),
-- | If True, keeps running regardless of success.
dontEnd :: Bool,
-- | Whether of not to use downsampling.
enableDownsampling :: Bool,
-- | The downsample function to use. "caseRand", "caseMaxim", "caseMaximAuto".
downsampleFunction :: String,
-- | Proportion of data used in downsample.
downsampleRate :: Float,
-- | Proportion of parents used to evaluate case distances.
downsampleParentRate :: Float,
-- | Amount of generations between parent distance computation
downsampleParentsGens :: Int,
-- | Whether or not to add the best individual to the next generation.
elitism :: Bool,
-- | User must provide their own error function.
-- Arg 1: PushArgs for the current set of arguments.
-- Arg 2: [PushData] is the input data.
-- Arg 3: [Gene] is the plushy representation of a program.
-- Returns the error list for a given set of inputs of type [Double].
errorFunction :: PushArgs -> [PushData] -> [Gene] -> [Double],
-- | Type of informed downsampling. "solved", "elite", "soft".
informedDownsamplingType :: String,
-- | List of instructions to use in the evolutionary run.
instructionList :: [Gene],
-- | For motely batch lexicase selection, max size of a batch of cases.
maxMotelyBatchSize :: Int,
-- | Max size of plushy genomes in a population.
maxInitialPlushySize :: Int,
-- | Maximum amount of generations allowed in an evolutionary run.
maxGenerations :: Int,
-- | Type of parent selection to use. Options are: "tournament","lexicase","epsilonLexicase".
parentSelectionAlgo :: String,
-- |Size of the population in the evolutionary run.
populationSize :: Int,
-- | For uniform replacement, rate of item replacement. A number in the bounds of [1,100].
replacementRate :: Double,
-- | Whether or not to auto simplify solutions.
useSimplification :: Bool,
-- | When auto simplifying, max amt items deleted in a single step.
simplificationMaxAmt :: Int,
-- | When auto simplifying, number of simplification steps.
simplificationSteps :: Int,
-- | When auto simplifying, whether to print verbose information.
simplificationVerbose :: Bool,
-- | Whether to use mutli-threading.
useMultiThreading :: Bool,
-- | Max total error for solutions.
solutionErrorThreshold :: Double,
-- | Limit of push interpreter steps in push program evaluation.
stepLimit :: Int,
-- | For tournament selection, amount of individuals in each tournament.
tournamentSize :: Int,
-- | Training data for the gp, must be provided.
trainingData :: [PushData],
-- | Testing data for the gp, must be provided if there is any.
testingData :: [PushData],
-- | Addition rate for UMAD (deletion rate derived from this). Should be an Int [0-100].
umadRate :: Double,
-- | Genetic operators and probabilities for their use, should sum to one
-- Takes a Map of String -> Float where the string is the genetic operator
variation :: [(String,Double)],
-- | The epsilons calculated for epsilon lexicase selection. Only used for epsilon lexicase selection.
epsilons :: Maybe [Double],
-- | Used with the CaseMaxminAuto downsampling strategy. Tells downsampling to stop when
-- the maximum minimum distance is too far away.
caseDelta :: Double,
-- | Used in lexicase selection. If initialCases is present will use those before randomly
-- selecting from the population for initial cases. Can raise a value into the IO monad using
-- `pure @IO`
initialCases :: Maybe [Int]
}
-- | The default values for which all runs of Hush derive
-- their args from.
defaultPushArgs :: PushArgs
defaultPushArgs = PushArgs {
alignmentDeviation = 2.0,
alternationRate = 0.1,
bmxExchangeRate = 0.5,
bmxGeneLengthLimit = 10,
bmxGapChangeProbability = 0.001,
bmxIsComplementary = False,
bmxMaxDistance = 1000000,
bmxSameGeneCount = False,
closes = "specified",
useBMX = False,
customReport = Nothing,
dontEnd = False,
enableDownsampling = True,
downsampleFunction = "caseMaxim",
downsampleRate = 0.05,
downsampleParentRate = 0.01,
downsampleParentsGens = 10,
elitism = False,
errorFunction = error "Must supply the error function yourself",
informedDownsamplingType = "solved",
instructionList = allInstructions,
maxMotelyBatchSize = 10,
maxInitialPlushySize = 100,
maxGenerations = 1000,
parentSelectionAlgo = "lexicase",
populationSize = 1000,
replacementRate = 0.1,
useSimplification = True,
simplificationMaxAmt = 4,
simplificationSteps = 1000,
simplificationVerbose = False,
useMultiThreading = False, -- False for now, change to True later.
solutionErrorThreshold = 0.0,
ssxNotBmx = False,
stepLimit = 1000,
tournamentSize = 5,
testingData = error "Must supply the testingData yourself",
trainingData = error "Must supply the trainingData yourself",
umadRate = 0.1,
variation = [("umad", 1.0)],
epsilons = Nothing,
caseDelta = 0,
initialCases = Nothing
}

36
src/HushGP/GP/PushData.hs Normal file
View File

@ -0,0 +1,36 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.GP.PushData where
import HushGP.State
import Control.Lens
data PushData = PushData {
_inputData :: [Gene],
_outputData :: Gene,
_downsampleIndex :: Maybe Int,
_caseDistances :: Maybe [Double]
} deriving (Show)
-- |Extracts any value from a list [PushData] based on their accessor and places the result back
-- into a list.
extractField :: Lens' PushData a -> [PushData] -> [a]
extractField accessor pushData = [ view accessor dataPoint | dataPoint <- pushData ]
-- |Extracts the case distances from a PushData object. Errors if the
-- _caseDistances list is Nothing.
extractDistance :: PushData -> [Double]
extractDistance PushData{_caseDistances = Nothing} = error "Error: Case distances are Nothing!. They should be assigned first!"
extractDistance PushData{_caseDistances = Just xs} = xs
-- |Extracts the downsample index from a PushData object. Errors if the
-- _downsampleIndex is Nothing.
extractIndex :: PushData -> Int
extractIndex PushData{_downsampleIndex = Nothing} = error "Error: Downsample index is empty!. They should be assigned first!"
extractIndex PushData{_downsampleIndex = Just x} = x
-- |Filters a list by another list of indices.
filterByIndex :: [a] -> [Int] -> [a]
filterByIndex origList = map (origList !!)
$(makeLenses ''PushData)

104
src/HushGP/GP/Selection.hs Normal file
View File

@ -0,0 +1,104 @@
module HushGP.GP.Selection where
import Numeric.Statistics.Median (medianFast)
import Data.List
import Data.Maybe
import System.Random
import HushGP.GP.PushArgs
import HushGP.GP.Individual
import HushGP.Utility
-- | Tournament selection based off tournament size from PushArgs and a population.
-- Takes the individual with the lowest total error in the tournament.
tournamentSelection :: PushArgs -> [Individual] -> IO Individual
tournamentSelection PushArgs{tournamentSize = tSize} pop = do
shuffledPop <- fst. uniformShuffleList pop <$> initStdGen
let tournSet = take tSize shuffledPop
pure $ minimum tournSet
-- |Selects an individual from the population using lexicase selection.
-- Lexicase parent selection filters the population by considering one random training case at a time,
-- eliminating any individuals with errors for the current case that are worse than the best error in the selection pool,
-- until a single individual remains. This is the top level function.
lexicaseSelection :: PushArgs -> [Individual] -> IO Individual
lexicaseSelection PushArgs{initialCases = iCases} pop = do
startCases <- maybe (fst . uniformShuffleList [0..lehp] <$> initStdGen) (pure @IO) iCases
survivors <- mapM randElem (groupBy (\x y -> fitnessCases x == fitnessCases y) pop)
lexicaseSelection' survivors startCases startCases
where
lehp :: Int -- length of the extracted fitness cases of the head of the passed population.
lehp = length $ extractFitnessCases $
case uncons pop of
Just (x, _) -> x
_ -> error "Error: Population in lexicaseSelection cannot be empty!"
-- |The internals of lexicaseSelection selection. Loops for each of the survivors each lexicase loop.
lexicaseSelection' :: [Individual] -> [Int] -> [Int] -> IO Individual
lexicaseSelection' survivors cases initialCases =
if null cases || null (drop 1 survivors)
then (\ind -> ind{selectionCases = Just initialCases}) <$> randElem survivors
else lexicaseSelection'
(filter (\ind -> (extractFitnessCases ind !! case uncons cases of Just (x, _) -> x; _ -> error "Error: cases list is empty!") == minErrorForCase) survivors)
(drop 1 cases)
initialCases
where
minErrorForCase :: Double
minErrorForCase = minimum $ map ((\x -> x !! case uncons cases of Just (y, _) -> y; _ -> error "Error: cases is empty!") . extractFitnessCases) survivors
-- |Calculates the median absolute deviation for a list of fractional numbers.
medianAbsoluteDeviation :: forall a. (Fractional a, Ord a) => [a] -> a
medianAbsoluteDeviation xs = medianFast $ map (\x -> abs (x - medianVal)) xs
where
medianVal :: a
medianVal = medianFast xs
-- | Calculates the epsilon list of a given population. Used in epsilon lexicase selection.
epsilonList :: [Individual] -> [Double]
epsilonList pop = epsilonList' [] 0 errorList errorLength
where
errorList :: [[Double]]
errorList = map extractFitnessCases pop
errorLength :: Int
errorLength = length $ extractFitnessCases (case uncons pop of Just (x, _) -> x; _ -> error "Error: pop is empty in epsilonList!")
-- | Internals for the epsilonList function.
epsilonList' :: [Double] -> Int -> [[Double]] -> Int -> [Double]
epsilonList' epsilons index errorList errorLength =
if index == errorLength
then epsilons
else epsilonList' (medianAbsoluteDeviation (map (!! index) errorList) : epsilons) (succ index) errorList errorLength
-- |Selects an individual from the population using epsilon-lexicase selection.
-- Epsilon lexicase selection follows the same process as lexicase selection except,
-- for a test case, only individuals with an error outside of a predefined epsilon are filtered.
epsilonLexicaseSelection :: PushArgs -> [Individual] -> IO Individual
epsilonLexicaseSelection PushArgs{epsilons = eps} pop = do
startCases <- fst . uniformShuffleList [0..lehp] <$> initStdGen
epsilonLexicaseSelection' (fromMaybe (error "Error: epsilons list is empty!") eps) pop startCases
where
lehp :: Int -- length of the extracted fitness cases of the head of the passed population.
lehp = length $ extractFitnessCases $
case uncons pop of
Just (x, _) -> x
_ -> error "Error: Population in epsilonLexicaseSelection cannot be empty!"
-- |Internals for epsilon lexicase selection.
epsilonLexicaseSelection' :: [Double] -> [Individual] -> [Int] -> IO Individual
epsilonLexicaseSelection' eps survivors cases =
if null cases || null (drop 1 survivors)
then randElem survivors
else epsilonLexicaseSelection' eps (filter (\x -> (abs (extractFitnessCases x !! headCases cases) - minErrorForCase) <= epsilon) survivors) (drop 1 cases)
where
minErrorForCase :: Double
minErrorForCase = minimum $ map ((\x -> x !! headCases cases) . extractFitnessCases) survivors
epsilon :: Double
epsilon = eps !! headCases cases
-- |Select the selection method the user specified in the passed PushArgs.
selectParent :: PushArgs -> [Individual] -> IO Individual
selectParent pushArgs@PushArgs{parentSelectionAlgo = selAlgo} pop =
case selAlgo of
"tournament" -> tournamentSelection pushArgs pop
"lexicase" -> lexicaseSelection pushArgs pop
"epsilonLexicase" -> epsilonLexicaseSelection pushArgs pop
_ -> error "Error: selection strategy not found!"

View File

@ -0,0 +1,46 @@
module HushGP.GP.Simplification where
import System.Random
import Control.Monad
import Data.List
import HushGP.State
import HushGP.GP.PushArgs
-- | Takes a list of Genes (a plushy), chunks it up into sizes of 1 (type is [[Gene]]).
-- and a list of indices for replacement (gets sorted before replacement).
deleteAtMultiple :: [Int] -> [Gene] -> [Gene]
deleteAtMultiple idxs = deleteAtMultiple' 0 (sort idxs)
-- | Internals of replaceAtMultiple. Takes a chunked plushy and replaces indices
-- that match the current index as specified at the idx.
deleteAtMultiple' :: Int -> [Int] -> [Gene] -> [Gene]
deleteAtMultiple' _ [] plushy = plushy
deleteAtMultiple' _ _ [] = []
deleteAtMultiple' curr (idx:idxs) (plushyPiece:plushy) =
if curr == idx then deleteAtMultiple' (curr + 1) idxs plushy else plushyPiece : deleteAtMultiple' (curr + 1) (idx:idxs) plushy
-- | Deletes a random amount of genes from the passed plushy based on ant int.
deleteRandomAmt :: Int -> [Gene] -> IO [Gene]
deleteRandomAmt k plushy = do
randomIndicies <- take k . fst . uniformShuffleList [0..(length plushy - 1)] <$> initStdGen
pure $ deleteAtMultiple randomIndicies plushy
-- | Simplifies a Plushy by randomly deleting instructions and seeing how it impacts
-- performance. Removes genes that have zero to negative performance impact.
autoSimplifyPlushy :: PushArgs -> [Gene] -> IO [Gene]
autoSimplifyPlushy pushArgs@PushArgs{simplificationVerbose = simpVerbose, errorFunction = eFunc, trainingData = tData} plushy = do
when simpVerbose (print ("simplification start plushy length: " <> show (length plushy)))
autoSimplifyPlushy' pushArgs (eFunc pushArgs tData plushy) 0 plushy
-- | Internals for autosimplification. Keeps track of the amount of steps.
autoSimplifyPlushy' :: PushArgs -> [Double] -> Int -> [Gene] -> IO [Gene]
autoSimplifyPlushy' pushArgs@PushArgs{simplificationVerbose = simpVerbose, simplificationSteps = simpSteps, simplificationMaxAmt = simpK, errorFunction = eFunc, trainingData = tData} initialErrors step plushy
| step < simpSteps = do
randAmt <- fst . uniformR (1 :: Int, simpK) <$> initStdGen
newPlushy <- deleteRandomAmt randAmt plushy
let newPlushyErrors = eFunc pushArgs tData newPlushy
let isBetter = newPlushyErrors <= initialErrors
autoSimplifyPlushy' pushArgs initialErrors (succ step) (if isBetter then newPlushy else plushy)
| otherwise = do
when simpVerbose (print ("simplification end plushy length: " <> show (length plushy)))
pure plushy

185
src/HushGP/GP/Variation.hs Normal file
View File

@ -0,0 +1,185 @@
module HushGP.GP.Variation where
import Data.List
import Control.Monad
import System.Random
import HushGP.State
import HushGP.GP.PushArgs
import HushGP.GP.Individual
import HushGP.Utility
import HushGP.Genome
import HushGP.GP.Selection
-- |Performs a uniform crossover on two parents and returns the child.
-- Padding is placed to left of the shorter genome.
crossover :: [Gene] -> [Gene] -> IO [Gene]
crossover plushyA plushyB = do
filter (CrossoverPadding /=) <$> zipWithM (\short long -> randZeroToOne >>= (\num -> if num < 0.5 then pure short else pure long)) shorterPadded longer
where
shorter :: [Gene]
shorter = if length plushyA <= length plushyB then plushyA else plushyB
longer :: [Gene]
longer = if length plushyA > length plushyB then plushyA else plushyB
lengthDiff :: Int
lengthDiff = length longer - length shorter
shorterPadded :: [Gene]
shorterPadded = shorter <> replicate lengthDiff CrossoverPadding
-- |Alternates between placing genes from one parent to the other in a new child based on some random numbers.
alternation :: PushArgs -> [Gene] -> [Gene] -> IO [Gene]
alternation pushArgs plushyA plushyB = do
randUsePlushyA <- randElem [True, False]
alternation' pushArgs 0 randUsePlushyA [] (length plushyA + length plushyB) plushyA plushyB
-- |This is a chunker. The PushArgs used in the whole evolutionary run.
-- The first Int is used in the gaussian noise calculation and as a stop condition.
-- The Bool is used to determine which plushy is used to copy to the child.
-- The first [Gene] is the child being created recursively.
-- The second int is the iteration budget. Used to stop very long looping.
-- The second [Gene] is the first plushy parent.
-- The third [Gene] is the second plushy parent.
-- This returns the first [Gene] when the loop is complete.
alternation' :: PushArgs -> Int -> Bool -> [Gene] -> Int -> [Gene] -> [Gene] -> IO [Gene]
alternation' pushArgs@PushArgs{alternationRate = altRate, alignmentDeviation = alignDeviation} n usePlushyA !resultPlushy iterationBudget plushyA plushyB = do
randNum <- randZeroToOne
let nextAction
| n >= length (if usePlushyA then plushyA else plushyB) || iterationBudget <= 0 = pure resultPlushy
| randNum < altRate = do
gNoiseFactor <- gaussianNoiseFactor
alternation' pushArgs (max 0 (n + round (gNoiseFactor * alignDeviation))) (not usePlushyA) resultPlushy (pred iterationBudget) plushyA plushyB
| otherwise = alternation' pushArgs (succ n) usePlushyA (resultPlushy <> [(if usePlushyA then plushyA else plushyB) !! n]) (pred iterationBudget) plushyA plushyB
nextAction
-- |Performs a uniform crossover on two parents and returns the child.
-- Padding is placed to left of the shorter genome.
tailAlignedCrossover :: [Gene] -> [Gene] -> IO [Gene]
tailAlignedCrossover plushyA plushyB = do
filter (CrossoverPadding /=) <$> zipWithM (\short long -> randZeroToOne >>= (\num -> if num < 0.5 then pure short else pure long)) shorterPadded longer
where
shorter :: [Gene]
shorter = if length plushyA <= length plushyB then plushyA else plushyB
longer :: [Gene]
longer = if length plushyA > length plushyB then plushyA else plushyB
lengthDiff :: Int
lengthDiff = length longer - length shorter
shorterPadded :: [Gene]
shorterPadded = replicate lengthDiff CrossoverPadding <> shorter
-- |Takes the PushArgs for the evolutionary run and a singular plushy.
-- Returns the added onto plushy. Returns the the passed plushy with
-- new instructions possibly added before or after each existing instruction.
uniformAddition :: PushArgs -> [Gene] -> IO [Gene]
uniformAddition pushArgs plushy = uniformAddition' pushArgs plushy []
-- |Guts of uniform addition. Appends to the second [Gene] recursively until the first [Gene]
-- is empty. Ignores Gaps used for bmx if applicable.
uniformAddition' :: PushArgs -> [Gene] -> [Gene] -> IO [Gene]
uniformAddition' _ [] newPlushy = pure newPlushy
uniformAddition' pushArgs@PushArgs{instructionList = iList, umadRate = uRate} (old:oldList) !newList = do
frontInstruction <- randomInstruction iList
backInstruction <- randomInstruction iList
frontZeroToOne <- randZeroToOne
backZeroToOne <- randZeroToOne
uniformAddition' pushArgs oldList (newList <> [frontInstruction | frontZeroToOne < uRate && not (isGap old)] <> [old] <> [backInstruction | backZeroToOne < uRate && not (isGap old)])
-- |Takes the PushArgs for the evolutionary run and a singular plushy.
-- Returns the replacement plushy. Returns the the passed plushy with
-- new instructions possibly replacing each existing instruction.
uniformReplacement :: PushArgs -> [Gene] -> IO [Gene]
uniformReplacement pushArgs plushy = uniformAddition' pushArgs plushy []
-- |Guts of uniform replacement. Appends to the second [Gene] recursively until the first [Gene]
-- is empty.
uniformReplacement' :: PushArgs -> [Gene] -> [Gene] -> IO [Gene]
uniformReplacement' _ [] newPlushy = pure newPlushy
uniformReplacement' pushArgs@PushArgs{instructionList = iList, replacementRate = rRate} (old:oldList) !newList = do
randInstruction <- randomInstruction iList
randDecimal <- randZeroToOne
uniformReplacement' pushArgs oldList (newList <> if randDecimal < rRate then [randInstruction] else [old])
-- |Takes the PushArgs for the evolutionary run and a singular plushy.
-- Returns the deleted plushy. Returns the passed plushy with
-- instructions that were there possibly deleted. Ignores Gaps used for bmx if applicable.
uniformDeletion :: PushArgs -> [Gene] -> IO [Gene]
uniformDeletion PushArgs{umadRate = uRate} plushy =
if uRate == 0
then pure plushy
else uniformDeletion' plushy [] adjustedRate
where
adjustedRate :: Double
adjustedRate = 1 / (1 + (1 / uRate))
-- |Internals for uniform deletion. The Double is the adjusted rate
-- calculated based on the original umad rate.
uniformDeletion' :: [Gene] -> [Gene] -> Double -> IO [Gene]
uniformDeletion' [] newPlushy _ = pure newPlushy
uniformDeletion' (old:oldList) !newList adjustRate = do
randDecimal <- randZeroToOne
uniformDeletion' oldList (newList <> [old | randDecimal < adjustRate]) adjustRate
-- |Creates a new individual based on the probabilities of the desired
-- crossover methods.
newIndividual :: PushArgs -> [Individual] -> IO Individual
newIndividual pushArgs@PushArgs{variation = var, umadRate = uRate} population = do
randOp <- randomOperation var 0.0
case randOp of
"reproduction" -> selectParent pushArgs population
"crossover" -> do
parent0 <- selectParent pushArgs population
parent1 <- selectParent pushArgs population
childPlushy <- crossover (plushy parent0) (plushy parent1)
pure $ postVariationInd childPlushy
"tailAlignedCrossover" -> do
parent0 <- selectParent pushArgs population
parent1 <- selectParent pushArgs population
childPlushy <- tailAlignedCrossover (plushy parent0) (plushy parent1)
pure $ postVariationInd childPlushy
"umad" -> do
parent <- selectParent pushArgs population
childPlushy <- uniformAddition pushArgs (plushy parent) >>= uniformDeletion pushArgs
pure $ postVariationInd childPlushy
"alternation" -> do
parent0 <- selectParent pushArgs population
parent1 <- selectParent pushArgs population
childPlushy <- alternation pushArgs (plushy parent0) (plushy parent1)
pure $ postVariationInd childPlushy
"rumad" -> do -- Responsive umad, deletion rate from computed amount of additions.
parent <- selectParent pushArgs population
addedChildPlushy <- uniformAddition pushArgs (plushy parent)
let effectiveAdditionRate = fromIntegral @Int @Double (length addedChildPlushy - length (plushy parent)) / fromIntegral @Int @Double (length (plushy parent))
finalChild <- uniformDeletion pushArgs{umadRate = effectiveAdditionRate} addedChildPlushy
pure $ postVariationInd finalChild
"vumad" -> do -- variable umad, umad rate chosen randomly from [0, umadRate]
rate <- fst . uniformR (0.0 :: Double, uRate) <$> initStdGen
parent <- selectParent pushArgs population
addedChildPlushy <- uniformAddition pushArgs{umadRate = rate} (plushy parent)
deletedChildPlushy <- uniformDeletion pushArgs{umadRate = rate} addedChildPlushy
pure $ postVariationInd deletedChildPlushy
"uniformAddition" -> do
parent <- selectParent pushArgs population
childPlushy <- uniformAddition pushArgs (plushy parent)
pure $ postVariationInd childPlushy
"uniformReplacement" -> do
parent <- selectParent pushArgs population
childPlushy <- uniformReplacement pushArgs (plushy parent)
pure $ postVariationInd childPlushy
"uniformDeletion" -> do
parent <- selectParent pushArgs population
childPlushy <- uniformDeletion pushArgs (plushy parent)
pure $ postVariationInd childPlushy
_ -> error ("Error: No match for selection operation: " <> randOp)
where
randDecimal :: IO Double
randDecimal = randZeroToOne
randomOperation :: [(String, Double)] -> Double -> IO String
randomOperation operations acc = do
randD <- randDecimal
let nextAction
| null operations = pure "reproduction"
| acc + tempProb >= randD = pure tempOp
| otherwise = randomOperation (drop 1 operations) (tempProb + acc)
nextAction
where
(tempOp,tempProb) = case uncons operations of Just (x, _) -> x; _ -> error "Error: operations cannot be empty!"

99
src/HushGP/Genome.hs Normal file
View File

@ -0,0 +1,99 @@
module HushGP.Genome where
import Data.List
import Data.List.Split
import Data.Map qualified as Map
import HushGP.GP.Individual
import HushGP.GP.PushArgs
import HushGP.Instructions.Opens
import HushGP.State
import HushGP.Utility
-- | Makes a random individual based on the variables in a passed PushArgs.
makeRandomIndividual :: PushArgs -> IO Individual
makeRandomIndividual pushArgs = do
randomPlushy <- makeRandomPlushy pushArgs
return Individual {plushy = randomPlushy, totalFitness = Nothing, fitnessCases = Nothing, selectionCases = Nothing}
-- | Makes a random plushy from variables in a passed PushArgs.
makeRandomPlushy :: PushArgs -> IO [Gene]
makeRandomPlushy PushArgs {maxInitialPlushySize = maxInitPSize, instructionList = iList} = randomInstructions maxInitPSize iList
-- | A utility function to generate an amount based on an int rather than
-- from an argmap.
makeRandomPlushy' :: Int -> [Gene] -> IO [Gene]
makeRandomPlushy' = randomInstructions
-- | Checks to see if a Gene is an (Open _) constructor.
isOpen :: Gene -> Bool
isOpen (Open _) = True
isOpen _ = False
-- | Decrements the count of an (Open _) constructor. Acts as id
-- if the gene isn't an open.
decOpen :: Gene -> Gene
decOpen (Open n) = Open (n - 1)
decOpen gene = gene
-- | Checks to see if the a list of genes with a single element is an opener.
isOpenerList :: [Gene] -> Bool
isOpenerList [instruction] =
case Map.lookup instruction instructionOpens of
Just _ -> True
_ -> False
isOpenerList _ = False
-- | Checks if the Gene is a Gap, returns True if it is.
isGap :: Gene -> Bool
isGap Gap = True
isGap _ = False
-- | Gets the amount of blocks to open from a list of genes with a single element.
getOpenAmountList :: [Gene] -> Int
getOpenAmountList [instruction] =
case Map.lookup instruction instructionOpens of
Just amt -> amt
_ -> 0
getOpenAmountList _ = 0
-- | Converts a plushy genome into a push genome.
plushyToPush :: PushArgs -> [Gene] -> [Gene]
plushyToPush PushArgs {useBMX = bmx} plushy = plushyToPush' modPlushy []
where
modPlushy :: [Gene]
modPlushy =
if bmx
then concatMap (filter (not . isGap) . (\x -> if isOpenerList x then x <> [Open (getOpenAmountList x)] else x)) (chunksOf 1 plushy)
else concatMap (\x -> if isOpenerList x then x <> [Open (getOpenAmountList x)] else x) (chunksOf 1 plushy)
-- | Internal function used to convert a plushy genome with opens in it into its push phenotype.
plushyToPush' :: [Gene] -> [Gene] -> [Gene]
plushyToPush' openPlushy push
| null openPlushy =
if any isOpen push
then plushyToPush' [Close] push
else push
| firstPlushy == Close =
if any isOpen push
then plushyToPush' (drop 1 openPlushy) (if numOpen (push !! openIndex) == 1 then preOpen <> [Block postOpen] else preOpen <> [Block postOpen] <> [decOpen (Open (numOpen (push !! openIndex)))])
else plushyToPush' (drop 1 openPlushy) push
| firstPlushy == Skip =
case uncons openPlushy of
Just (_, _ : xs) -> plushyToPush' xs push
_ -> plushyToPush' (drop 1 openPlushy) push
| otherwise = plushyToPush' (drop 1 openPlushy) (push <> [firstPlushy])
where
firstPlushy :: Gene
firstPlushy =
case uncons openPlushy of
Just (g, _) -> g
_ -> error "Error: First plushy taken when no plushy available!"
postOpen :: [Gene]
postOpen = reverse (takeWhile (not . isOpen) (reverse push))
openIndex :: Int
openIndex = length push - length postOpen - 1
numOpen :: Gene -> Int
numOpen (Open n) = n
numOpen _ = 0
preOpen :: [Gene]
preOpen = take openIndex push

View File

@ -0,0 +1,56 @@
module HushGP.Instructions
( module HushGP.Instructions.GenericInstructions,
module HushGP.Instructions.IntInstructions,
module HushGP.Instructions.FloatInstructions,
module HushGP.Instructions.StringInstructions,
module HushGP.Instructions.CharInstructions,
module HushGP.Instructions.CodeInstructions,
module HushGP.Instructions.ExecInstructions,
module HushGP.Instructions.BoolInstructions,
module HushGP.Instructions.VectorIntInstructions,
module HushGP.Instructions.VectorFloatInstructions,
module HushGP.Instructions.VectorStringInstructions,
module HushGP.Instructions.VectorBoolInstructions,
module HushGP.Instructions.VectorCharInstructions,
allInstructions,
)
where
import HushGP.Instructions.BoolInstructions
import HushGP.Instructions.CharInstructions
import HushGP.Instructions.CodeInstructions
import HushGP.Instructions.ExecInstructions
import HushGP.Instructions.FloatInstructions
import HushGP.Instructions.GenericInstructions
import HushGP.Instructions.IntInstructions
import HushGP.Instructions.StringInstructions
import HushGP.Instructions.VectorBoolInstructions
import HushGP.Instructions.VectorCharInstructions
import HushGP.Instructions.VectorFloatInstructions
import HushGP.Instructions.VectorIntInstructions
import HushGP.Instructions.VectorStringInstructions
import HushGP.State
noOpStateFunc :: Gene
noOpStateFunc = StateFunc (instructionNoOp, "instructionNoOp")
noOpStateFuncBlock :: Gene
noOpStateFuncBlock = StateFunc (instructionNoOpBlock, "instructionNoOpBlock")
-- | All of the instructions declared in all the instruction submodules
allInstructions :: [Gene]
allInstructions =
noOpStateFunc
: noOpStateFuncBlock
: allIntInstructions
<> allFloatInstructions
<> allBoolInstructions
<> allCharInstructions
<> allCodeInstructions
<> allExecInstructions
<> allStringInstructions
<> allVectorIntInstructions
<> allVectorFloatInstructions
<> allVectorCharInstructions
<> allVectorStringInstructions
<> allVectorBoolInstructions

View File

@ -0,0 +1,101 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.BoolInstructions where
import HushGP.State
import HushGP.Instructions.GenericInstructions
import HushGP.Instructions.Utility
import HushGP.TH
-- |If top of int stack /= 0 pushes True to bool stack, else false.
instructionBoolFromInt :: State -> State
instructionBoolFromInt state@(State {_int = i1 : is, _bool = bs}) = state {_int = is, _bool = (i1 /= 0) : bs}
instructionBoolFromInt state = state
-- |If top of float stack /= 0 pushes True to bool stack, else false.
instructionBoolFromFloat :: State -> State
instructionBoolFromFloat state@(State {_float = f1 : fs, _bool = bs}) = state {_float = fs, _bool = (f1 /= 0) : bs}
instructionBoolFromFloat state = state
-- |Takes the top two bools and Ands them.
instructionBoolAnd :: State -> State
instructionBoolAnd = boolTemplate (&&)
-- |Takes the top two bools, inverts the first bool and then Ands the modified state.
instructionBoolInvertFirstThenAnd :: State -> State
instructionBoolInvertFirstThenAnd state@(State {_bool = b1 : bs}) = boolTemplate (&&) state {_bool = not b1 : bs}
instructionBoolInvertFirstThenAnd state = state
-- |Takes the top two bools, inverts the second bool and then Ands the modified state.
instructionBoolInvertSecondThenAnd :: State -> State
instructionBoolInvertSecondThenAnd state@(State {_bool = b1 : b2 : bs}) = boolTemplate (&&) state {_bool = b1 : not b2 : bs}
instructionBoolInvertSecondThenAnd state = state
-- |Takes the top two bools and Ors them.
instructionBoolOr :: State -> State
instructionBoolOr = boolTemplate (||)
-- |Takes the xor of the top two bools.
instructionBoolXor :: State -> State
instructionBoolXor = boolTemplate xor
-- |Pops the top of the bool stack.
instructionBoolPop :: State -> State
instructionBoolPop = instructionPop bool
-- |Duplicates the top of the bool stack.
instructionBoolDup :: State -> State
instructionBoolDup = instructionDup bool
-- |Duplicates the top of the bool stack based on the top int from the int stack.
instructionBoolDupN :: State -> State
instructionBoolDupN = instructionDupN bool
-- |Swaps the top two bools.
instructionBoolSwap :: State -> State
instructionBoolSwap = instructionSwap bool
-- |Rotates the top three bools.
instructionBoolRot :: State -> State
instructionBoolRot = instructionRot bool
-- |Sets the bool stack to []
instructionBoolFlush :: State -> State
instructionBoolFlush = instructionFlush bool
-- |Tests if the top two bools are equal and pushes the result to the bool stack.
instructionBoolEq :: State -> State
instructionBoolEq = instructionEq bool
-- |Calculates the size of a stack and pushes the result to the int stack.
instructionBoolStackDepth :: State -> State
instructionBoolStackDepth = instructionStackDepth bool
-- |Moves an item from deep within the bool stack to the top of the bool stack based on
-- the top int from the int stack
instructionBoolYank :: State -> State
instructionBoolYank = instructionYank bool
-- |Copies an item from deep within the bool stack to the top of the bool stack based on
-- the top int from the int stack.
instructionBoolYankDup :: State -> State
instructionBoolYankDup = instructionYankDup bool
-- |Moves an item from the top of the bool stack to deep within the bool stack based on
-- the top int from the int stack.
instructionBoolShove :: State -> State
instructionBoolShove = instructionShove bool
-- |Copies an item from the top of the bool stack to deep within the bool stack based on
-- the top int from the int stack.
instructionBoolShoveDup :: State -> State
instructionBoolShoveDup = instructionShoveDup bool
-- |If the bool stack is empty, pushes True to bool stack, else False.
instructionBoolIsStackEmpty :: State -> State
instructionBoolIsStackEmpty = instructionIsStackEmpty bool
-- |Duplicate the top N items from the bool stack based on the top int from the int stack.
instructionBoolDupItems :: State -> State
instructionBoolDupItems = instructionDupItems bool
allBoolInstructions :: [Gene]
allBoolInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,139 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.CharInstructions where
import Data.Char
import HushGP.State
import HushGP.Instructions.GenericInstructions
import HushGP.Instructions.Utility
import HushGP.TH
-- |Combines the top two chars into a string and pushes the result to the string stack.
instructionCharConcat :: State -> State
instructionCharConcat state@(State {_char = c1 : c2 : cs, _string = ss}) = state{_char = cs, _string = [c1, c2] : ss}
instructionCharConcat state = state
-- |Takes the first char from the top string and pushes it to the char stack.
-- If the string is empty, acts as a no-op.
instructionCharFromFirstChar :: State -> State
instructionCharFromFirstChar = instructionVectorFirst char string
-- |Takes the last char from the top string and pushes it to the char stack.
-- If the string is empty, acts as a no-op.
instructionCharFromLastChar :: State -> State
instructionCharFromLastChar = instructionVectorLast char string
-- |Takes the Nth char from the top string and pushes it to the char stack
-- based on the top int from the int stack. If the string is empty, acts as a no-op.
instructionCharFromNthChar :: State -> State
instructionCharFromNthChar = instructionVectorNth char string
-- |Takes the top of the char stack, checks to see if it is whitespace, and then
-- pushes True to the bool stack if so, else false.
instructionCharIsWhitespace :: State -> State
instructionCharIsWhitespace state@(State {_char = c1 : cs, _bool = bs}) = state{_char = cs, _bool = (c1 `elem` wschars) : bs}
instructionCharIsWhitespace state = state
-- |Takes the top of the char stack, checks to see if it is an alphabetic character, and
-- then pushes True to the bool stack if alphabetic, false if not.
instructionCharIsLetter :: State -> State
instructionCharIsLetter state@(State {_char = c1 : cs, _bool = bs}) = state{_char = cs, _bool = isAlpha c1 : bs}
instructionCharIsLetter state = state
-- |Takes the top of the char stack, checks to see if it is a digit, and then pushes True if it is
-- a digit, False if not.
instructionCharIsDigit :: State -> State
instructionCharIsDigit state@(State {_char = c1 : cs, _bool = bs}) = state{_char = cs, _bool = isDigit c1 : bs}
instructionCharIsDigit state = state
-- |Takes the top of the bool stack, pushes 'T' to the char stack if True, 'F' to the char stack if False.
instructionCharFromBool :: State -> State
instructionCharFromBool state@(State {_char = cs, _bool = b1 : bs}) = state{_char = (if b1 then 'T' else 'F') : cs, _bool = bs}
instructionCharFromBool state = state
-- |Takes the top of the int stack, pushes the ascii representation of the int to the char stack.
instructionCharFromAsciiInt :: State -> State
instructionCharFromAsciiInt state@(State {_char = cs, _int = i1 : is}) = state{_char = intToAscii i1 : cs, _int = is}
instructionCharFromAsciiInt state = state
-- |Takes the top of the float stack, pushes the ascii representation of the floored float to the char stack.
instructionCharFromAsciiFloat :: State -> State
instructionCharFromAsciiFloat state@(State {_char = cs, _float = f1 : fs}) = state{_char = intToAscii @Integer (floor f1) : cs, _float = fs}
instructionCharFromAsciiFloat state = state
-- |Pushes the top string to the char stack split up into individual chars.
-- For example: have the string "hello" and the char stack ['a', 'b', 'c'], the char stack
-- looks like ['h', 'e', 'l', 'l', 'o', 'a', 'b', 'c'] after this instruction executes.
instructionCharsFromString :: State -> State
instructionCharsFromString state@(State {_char = cs, _string = s1 : ss}) = state{_char = s1 <> cs, _string = ss}
instructionCharsFromString state = state
-- |Pops the top of the char stack.
instructionCharPop :: State -> State
instructionCharPop = instructionPop char
-- |Duplicates the top of the char stack.
instructionCharDup :: State -> State
instructionCharDup = instructionDup char
-- |Duplicates the top of the char stack N times based on the top of
-- int stack.
instructionCharDupN :: State -> State
instructionCharDupN = instructionDupN char
-- |Swaps the top two chars of the char stack.
instructionCharSwap :: State -> State
instructionCharSwap = instructionSwap char
-- |Rotates the top three chars of the char stack.
instructionCharRot :: State -> State
instructionCharRot = instructionRot char
-- |Sets the char stack to [].
instructionCharFlush :: State -> State
instructionCharFlush = instructionFlush char
-- |Checks to see if the top two chars to equal and pushes the result
-- to the bool stack.
instructionCharEq :: State -> State
instructionCharEq = instructionEq char
-- |Calculates the stack depth of the char stack. Pushes the result
-- to the int stack.
instructionCharStackDepth :: State -> State
instructionCharStackDepth = instructionStackDepth char
-- |Moves an item from deep within the char stack to the top of the char stack based on
-- the top int from the int stack.
instructionCharYank :: State -> State
instructionCharYank = instructionYank char
-- |Copies an item from deep within the char stack to the top of the char stack based on
-- the top int from the int stack.
instructionCharYankDup :: State -> State
instructionCharYankDup = instructionYankDup char
-- |Pushes True to the bool stack if the char stack is empty. False if not.
instructionCharIsStackEmpty :: State -> State
instructionCharIsStackEmpty = instructionIsStackEmpty char
-- |Moves an item from the top of the char stack to deep within the char stack based on
-- the top int from the int stack.
instructionCharShove :: State -> State
instructionCharShove = instructionShove char
-- |Copies an item from the top of the char stack to deep within the char stack based on
-- the top int from the int stack.
instructionCharShoveDup :: State -> State
instructionCharShoveDup = instructionShoveDup char
-- |Duplicate the top N items from the char stack based on the top int from the int stack.
instructionCharDupItems :: State -> State
instructionCharDupItems = instructionDupItems char
-- |Takes the top string from the string stack and invidually pushes
-- all chars in said string to the char stack.
instructionCharFromAllString :: State -> State
instructionCharFromAllString = instructionPushAll char string
allCharInstructions :: [Gene]
allCharInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,352 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.CodeInstructions where
import Data.List (elemIndex)
import HushGP.State
import HushGP.Instructions.GenericInstructions
import HushGP.Instructions.IntInstructions
import HushGP.Instructions.Utility
import HushGP.TH
-- import Debug.Trace
-- |Pops the top of the code stack
instructionCodePop :: State -> State
instructionCodePop = instructionPop code
-- |Checks if the top code item is a Block
instructionCodeIsCodeBlock :: State -> State
instructionCodeIsCodeBlock state@(State {_code = c1 : cs, _bool = bs}) = state {_code = cs, _bool = isBlock c1 : bs}
instructionCodeIsCodeBlock state = state
-- |Checks if the top code item is not a Block
instructionCodeIsSingular :: State -> State
instructionCodeIsSingular state@(State {_code = c1 : cs, _bool = bs}) = state {_code = cs, _bool = not (isBlock c1) : bs}
instructionCodeIsSingular state = state
-- |Checks the length of the top code item. If item is a block, counts the size, if not, returns 1
instructionCodeLength :: State -> State
instructionCodeLength state@(State {_code = c1 : cs, _int = is}) = state {_code = cs, _int = blockLength c1 : is}
instructionCodeLength state = state
-- CODE.CAR
-- |If the top item on the code stack is a Block, extracts the first item and places it onto the code stack. Acts as a NoOp otherwise.
instructionCodeFirst :: State -> State
instructionCodeFirst state@(State {_code = c1 : cs}) = state {_code = extractFirstFromBlock c1 : cs}
instructionCodeFirst state = state
-- |If the top item on the code stack is a Block, extracts the last item and places it onto the code stack. Acts as a NoOp otherwise.
instructionCodeLast :: State -> State
instructionCodeLast state@(State {_code = c1 : cs}) = state {_code = extractLastFromBlock c1 : cs}
instructionCodeLast state = state
-- |If the top item on the code stack is a Block, extracts the tail of said Block and places it onto the code stace. Acts as a NoOp otherwise.
-- CODE.CDR
-- https://erp12.github.io/pyshgp/html/core_instructions.html#code-rest
instructionCodeTail :: State -> State
instructionCodeTail state@(State {_code = c1 : cs}) = state {_code = extractTailFromBlock c1 : cs}
instructionCodeTail state = state
-- |If the top item on the code stack is a Block, takes the tail of said block starting at an index determined by the int stack
-- and pushes the result to the code stack.
-- Acts as a NoOp if not a Block.
-- https://faculty.hampshire.edu/lspector/push3-description.html#Type
-- This is the CODE.NTHCDR command
instructionCodeTailN :: State -> State
instructionCodeTailN state@(State {_code = Block bc : cs, _int = i1 : is}) = state {_code = Block (drop index bc) : cs, _int = is}
where
index :: Int
index = fromIntegral (abs i1) `mod` length bc
instructionCodeTailN state = state
-- |If the top item on the code stack is a Block, takes the init of said Block and places the result on top of the code stack.
-- Acts as a NoOp otherwise
-- https://erp12.github.io/pyshgp/html/core_instructions.html#code-but-last
instructionCodeInit :: State -> State
instructionCodeInit state@(State {_code = c1 : cs}) = state {_code = extractInitFromBlock c1 : cs}
instructionCodeInit state = state
-- |Wraps the top item in the code stack in a Block no matter the type.
instructionCodeWrap :: State -> State
instructionCodeWrap state@(State {_code = c1 : cs}) = state {_code = Block [c1] : cs}
instructionCodeWrap state = state
-- |Wraps the top two items in the code stack in a Block no matter the type.
instructionCodeList :: State -> State
instructionCodeList state@(State {_code = c1 : c2 : cs}) = state {_code = Block [c1, c2] : cs}
instructionCodeList state = state
-- |Combines the top two items on the code stack based on whether they are a block or not.
-- Check out the codeCombine utility function for how this works.
instructionCodeCombine :: State -> State
instructionCodeCombine state@(State {_code = c1 : c2 : cs}) = state {_code = codeCombine c1 c2 : cs}
instructionCodeCombine state = state
-- |Moves the top item from the code stack to the exec stack
instructionCodeDo :: State -> State
instructionCodeDo state@(State {_code = c1 : cs, _exec = es}) = state {_code = cs, _exec = c1 : es}
instructionCodeDo state = state
-- |Moves the top item from the code stack to the exec stack, doesn't delete the original item from the code stack.
instructionCodeDoDup :: State -> State
instructionCodeDoDup state@(State {_code = c1 : cs, _exec = es}) = state {_code = c1 : cs, _exec = c1 : es}
instructionCodeDoDup state = state
-- |Places the top code item onto the exec stack (doesn't delete it from the code stack), then places an instructionCodePop onto
-- the exec stack.
-- https://erp12.github.io/pyshgp/html/core_instructions.html#code-do-then-pop
instructionCodeDoThenPop :: State -> State
instructionCodeDoThenPop state@(State {_code = c1 : _, _exec = es}) = state {_exec = c1 : StateFunc (instructionCodePop, "instructionCodePop") : es}
instructionCodeDoThenPop state = state
-- |Evaluates the top item on the code stack for each step along the range i to j. Both i and j are taken from the int stack.
instructionCodeDoRange :: State -> State
instructionCodeDoRange state@(State {_code = c1 : cs, _int = i0 : i1 : is, _exec = es}) =
if increment (fromIntegral i0) (fromIntegral i1) /= 0
then state {_exec = c1 : Block [GeneInt (i1 + toInteger (increment (fromIntegral i0) (fromIntegral i1))), GeneInt i0, StateFunc (instructionCodeFromExec, "instructionCodeFromExec"), c1, StateFunc (instructionCodeDoRange, "instructionCodeDoRange")] : es, _int = i1 : is, _code = cs}
else state {_exec = c1: es, _int = i1 : is, _code = cs}
where
increment :: Int -> Int -> Int
increment destIdx currentIdx
| currentIdx < destIdx = 1
| currentIdx > destIdx = -1
| otherwise = 0
instructionCodeDoRange state = state
-- |Evaluates the top item on the code stack for each step along the range i to j. Both i and j are taken from the int stack.
instructionCodeDoCount :: State -> State
instructionCodeDoCount state@(State {_code = c : cs, _int = i1 : is, _exec = es}) =
if i1 < 1
then state
else state {_code = cs, _int = is, _exec = Block [GeneInt 0, GeneInt $ i1 - 1, StateFunc (instructionCodeFromExec, "instructionCodeFromExec"), c, StateFunc (instructionCodeDoRange, "instructionCodeDoRange")] : es}
instructionCodeDoCount state = state
-- |Evaluates the top item on the code stack n times, where n comes from the n comes from the top of the int stack.
instructionCodeDoTimes :: State -> State
instructionCodeDoTimes state@(State {_code = c : cs, _int = i1 : is, _exec = es}) =
if i1 < 1
then state
else state {_code = cs, _int = is, _exec = Block [GeneInt 0, GeneInt $ i1 - 1, StateFunc (instructionCodeFromExec, "instructionCodeFromExec"), Block [StateFunc (instructionIntPop, "instructionIntPop"), c], StateFunc (instructionCodeDoRange, "instructionCodeDoRange")] : es}
instructionCodeDoTimes state = state
-- |If the top boolean is true, execute the top element of the code stack and skip the second. Otherwise, skip the top element of the code stack and execute the second.
instructionCodeIf :: State -> State
instructionCodeIf state@(State {_code = c1 : c2 : cs, _bool = b1 : bs, _exec = es}) = state{_code = cs, _bool = bs, _exec = (if b1 then c1 else c2) : es}
instructionCodeIf state = state
-- |Evalutates the top code item if the top bool is true. Otherwise the top code is popped.
instructionCodeWhen :: State -> State
instructionCodeWhen state@(State {_code = c1 : cs, _bool = b1 : bs, _exec = es}) = state{_code = cs, _bool = bs, _exec = if b1 then c1 : es else es}
instructionCodeWhen state = state
-- |Pushes true to the bool stack if the second to top code item is found within the first code item. Pushes False if not.
instructionCodeMember :: State -> State
instructionCodeMember state@(State {_code = c1 : c2 : cs, _bool = bs}) = state{_code = cs, _bool = codeMember c1 c2 : bs}
instructionCodeMember state = state
-- |Pushes the nth element from a Block onto the code stack based on an index from the int stack.
-- If the top of the code stack is not a block, the int is still eaten.
-- This one doesn't count the recursive Blocks while instructionCodeExtract does
-- https://erp12.github.io/pyshgp/html/core_instructions.html#code-nth
instructionCodeN :: State -> State
instructionCodeN state@(State {_code = (Block c1) : cs, _int = i1 : is}) =
if not $ null c1
then state {_code = c1 !! index : cs, _int = is}
else state
where
index :: Int
index = fromIntegral (abs i1) `mod` length c1
instructionCodeN state@(State {_code = c1 : cs, _int = _ : is}) = state {_code = c1 : cs, _int = is}
instructionCodeN state = state
-- |Makes an empty Block and pushes it to the top of the code stack.
instructionMakeEmptyCodeBlock :: State -> State
instructionMakeEmptyCodeBlock state@(State {_code = cs}) = state {_code = Block [] : cs}
-- |If the top of the code stack is a Block, pushes True to the bool stack if it is and False if it's not.
-- If the top item of the code stack is not a Block, False gets pushed to the bool stack
instructionIsEmptyCodeBlock :: State -> State
instructionIsEmptyCodeBlock state@(State {_code = Block c1 : cs, _bool = bs}) = state{_code = cs, _bool = null c1 : bs}
instructionIsEmptyCodeBlock state@(State {_code = _ : cs, _bool = bs}) = state{_code = cs, _bool = False : bs}
instructionIsEmptyCodeBlock state = state
-- |Pushes the size of the top code item to the int stack. If it's a Block, the size is counted recursively. If
-- it's not a Block, 1 gets pushed to the int stack.
instructionCodeSize :: State -> State
instructionCodeSize state@(State {_code = c1 : cs, _int = is}) = state{_code = cs, _int = codeRecursiveSize c1 : is}
instructionCodeSize state = state
-- |Pushes the size of the top code item recursively counting the nested Blocks.
-- There's a bug for this instruction in pysh where the last item in the
-- top level Block isn't counted, and if passed 0, then the entire codeblock is returned.
-- I designed this function differently so 0 returns the 0th element, and the last item
-- in the codeblock can be returned.
instructionCodeExtract :: State -> State
instructionCodeExtract state@(State {_code = block@(Block c1) : cs, _int = i1 : is}) =
let
index = abs i1 `mod` codeRecursiveSize block
in
state{_code = codeAtPoint c1 (fromIntegral index) : cs, _int = is}
instructionCodeExtract state@(State {_code = cs, _int = _ : is}) = state{_code = cs, _int = is}
instructionCodeExtract state = state
-- |Inserts a code item into a block recursively entering the nested Blocks if needed based on the top
-- int from the int stack. If the top code item isn't a Block, coerces the top item into a Block.
instructionCodeInsert :: State -> State
instructionCodeInsert state@(State {_code = block@(Block c1) : c2 : cs, _int = i1 : is}) =
let
index = abs i1 `mod` codeRecursiveSize block
in
state{_code = Block (codeInsertAtPoint c1 c2 (fromIntegral index)) : cs, _int = is}
instructionCodeInsert state@(State {_code = c1 : c2 : cs, _int = i1 : is}) =
let
index = abs i1 `mod` codeRecursiveSize (Block [c1])
in
state{_code = Block (codeInsertAtPoint [c1] c2 (fromIntegral index)) : cs, _int = is}
instructionCodeInsert state = state
-- |If the top code item is a Block that is empty, pushes 0 to the int stack if c2 is also an empty Block and -1 if not.
-- If the top code item is a Block that is not empty, pushes the index found of the second code item if found, -1 if not.
-- If neither the top code item or second code item are Blocks, checks equality. If equal, pushes 1 to int stack, pushes 0 if not.
instructionCodeFirstPosition :: State -> State
instructionCodeFirstPosition state@(State {_code = (Block []) : c2 : cs, _int = is}) = state {_code = cs, _int = (if c2 == Block [] then 0 else -1) : is}
instructionCodeFirstPosition state@(State {_code = (Block c1) : c2 : cs, _int = is}) = state {_code = cs, _int = fromIntegral (positionElem c1 c2) : is}
where
positionElem :: [Gene] -> Gene -> Int
positionElem genes gene =
case elemIndex gene genes of
Nothing -> -1
Just x -> x
instructionCodeFirstPosition state@(State {_code = c1 : c2 : cs, _int = is}) = state {_code = cs, _int = (if c1 == c2 then 0 else -1) : is}
instructionCodeFirstPosition state = state
-- |If the top of the code stack is a Block, reverses the elements of the Block. Acts as a NoOp otherwise.
instructionCodeReverse :: State -> State
instructionCodeReverse state@(State {_code = (Block c1) : cs}) = state {_code = Block (reverse c1) : cs}
instructionCodeReverse state = state
-- |Duplicates the top of the code stack.
instructionCodeDup :: State -> State
instructionCodeDup = instructionDup code
-- |Duplicates the top of the code stack N times based on the top int.
instructionCodeDupN :: State -> State
instructionCodeDupN = instructionDupN code
-- |Swaps the top two code items.
instructionCodeSwap :: State -> State
instructionCodeSwap = instructionSwap code
-- |Rotates the top three code items.
instructionCodeRot :: State -> State
instructionCodeRot = instructionRot code
-- |Sets the code stack to []
instructionCodeFlush :: State -> State
instructionCodeFlush = instructionFlush code
-- |Checks if the top code items are equal. Pushes True to the bool stack if so, False if not.
instructionCodeEq :: State -> State
instructionCodeEq = instructionEq code
-- |Pushes the size of the code stack to the int stack.
instructionCodeStackDepth :: State -> State
instructionCodeStackDepth = instructionStackDepth code
-- |Moves an item from deep within the code stack to the top of the code stack based on
-- the top int from the int stack.
instructionCodeYank :: State -> State
instructionCodeYank = instructionYank code
-- |Copies an item from deep within the code stack to the top of the code stack based on
-- the top int from the int stack.
instructionCodeYankDup :: State -> State
instructionCodeYankDup = instructionYankDup code
-- |If the code stack is empty, pushes True to bool stack, else False.
instructionCodeIsStackEmpty :: State -> State
instructionCodeIsStackEmpty = instructionIsStackEmpty code
-- |Moves an item from the top of the code stack to deep within the code stack based on
-- the top int from the int stack.
instructionCodeShove :: State -> State
instructionCodeShove = instructionShove code
-- |Copies an item from the top of the code stack to deep within the code stack based on
-- the top int from the int stack.
instructionCodeShoveDup :: State -> State
instructionCodeShoveDup = instructionShoveDup code
-- |Takes the top bool from the bool stack and places said GeneBool on the code stack.
instructionCodeFromBool :: State -> State
instructionCodeFromBool = instructionCodeFrom bool GeneBool
-- |Takes the top int from the int stack and places said GeneInt on the code stack.
instructionCodeFromInt :: State -> State
instructionCodeFromInt = instructionCodeFrom int GeneInt
-- |Takes the top char from the char stack and places said GeneChar on the code stack.
instructionCodeFromChar :: State -> State
instructionCodeFromChar = instructionCodeFrom char GeneChar
-- |Takes the top float from the float stack and places said GeneFloat on the code stack.
instructionCodeFromFloat :: State -> State
instructionCodeFromFloat = instructionCodeFrom float GeneFloat
-- |Takes the top string from the string stack and places said GeneString on the code stack.
instructionCodeFromString :: State -> State
instructionCodeFromString = instructionCodeFrom string GeneString
-- |Takes the top vectorInt from the vectorInt stack and places said GeneVectorInt on the code stack.
instructionCodeFromVectorInt :: State -> State
instructionCodeFromVectorInt = instructionCodeFrom vectorInt GeneVectorInt
-- |Takes the top vectorFloat from the vectorFloat stack and places said GeneVectorFloat on the code stack.
instructionCodeFromVectorFloat :: State -> State
instructionCodeFromVectorFloat = instructionCodeFrom vectorFloat GeneVectorFloat
-- |Takes the top vectorString from the vectorString stack and places said GeneVectorString on the code stack.
instructionCodeFromVectorString :: State -> State
instructionCodeFromVectorString = instructionCodeFrom vectorString GeneVectorString
-- |Takes the top vectorBool from the vectorBool stack and places said GeneVectorBool on the code stack.
instructionCodeFromVectorBool :: State -> State
instructionCodeFromVectorBool = instructionCodeFrom vectorBool GeneVectorBool
-- |Takes the top vectorChar from the vectorChar stack and places said GeneVectorChar on the code stack.
instructionCodeFromVectorChar :: State -> State
instructionCodeFromVectorChar = instructionCodeFrom vectorChar GeneVectorChar
-- |Takes the top gene from the exec stack and places a gene on the code stack.
instructionCodeFromExec :: State -> State
instructionCodeFromExec = instructionCodeFrom exec id
-- |Pushes the "container" of the second code stack item within
-- the first code stack item onto the code stack. If second item contains the first
-- anywhere (i.e. in any nested list) then the container is the smallest sub-list that
-- contains but is not equal to the first instance. For example, if the top piece of code
-- is "( B ( C ( A ) ) ( D ( A ) ) )" and the second piece of code is "( A )" then
-- this pushes ( C ( A ) ). Pushes an empty list if there is no such container.
instructionCodeContainer :: State -> State
instructionCodeContainer state@(State {_code = c1 : c2 : cs}) = state {_code = findContainer c1 c2 : cs}
instructionCodeContainer state = state
-- |Pushes a measure of the discrepancy between the top two CODE stack items onto the INTEGER stack. This will be zero if the top two items
-- are equivalent, and will be higher the 'more different' the items are from one another. The calculation is as follows:
-- 1. Construct a list of all of the unique items in both of the lists (where uniqueness is determined by equalp). Sub-lists and atoms all count as items.
-- 2. Initialize the result to zero.
-- 3. For each unique item increment the result by the difference between the number of occurrences of the item in the two pieces of code.
-- 4. Push the result.
instructionCodeDiscrepancy :: State -> State
instructionCodeDiscrepancy state@(State {_code = c1 : c2 : cs, _int = is}) = state {_code = cs, _int = countDiscrepancy c1 c2 : is}
instructionCodeDiscrepancy state = state
-- |Just a NoOp
instructionCodeNoOp :: State -> State
instructionCodeNoOp state = state
-- |Duplicates the top N items of the code stack based on the top of the int stack.
instructionCodeDupItems :: State -> State
instructionCodeDupItems = instructionDupItems code
allCodeInstructions :: [Gene]
allCodeInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,160 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.ExecInstructions where
import HushGP.State
import HushGP.Instructions.IntInstructions
import HushGP.Instructions.GenericInstructions
import HushGP.TH
-- |Removes the second item from the exec stack if the top of the bool stack is True.
-- Removes the first item from the exec stack if the top of the bool stack is False.
instructionExecIf :: State -> State
instructionExecIf state@(State {_exec = e1 : e2 : es, _bool = b1 : bs}) =
if b1
then state {_exec = e1 : es, _bool = bs}
else state {_exec = e2 : es, _bool = bs}
instructionExecIf state = state
-- |Duplicates the top exec instruction (the one after this one on the stack).
instructionExecDup :: State -> State
instructionExecDup = instructionDup exec
-- |Duplicates the top of the exec stack N times based on the top of
-- int stack (the exec instruction after this one).
instructionExecDupN :: State -> State
instructionExecDupN = instructionDupN exec
-- |Pops the top of the exec stack (the one after this on on the stack).
instructionExecPop :: State -> State
instructionExecPop = instructionPop exec
-- |Swaps the top two instructions on the exec stack (the two after this on the exec stack).
instructionExecSwap :: State -> State
instructionExecSwap = instructionSwap exec
-- |Rotates the top three instructions on the exec stack (the three after this on the exec stack).
instructionExecRot :: State -> State
instructionExecRot = instructionRot exec
-- |Sets the exec stack to []. This stops the program.
instructionExecFlush :: State -> State
instructionExecFlush = instructionFlush exec
-- |Checks if the top two exec instructions are True.
instructionExecEq :: State -> State
instructionExecEq = instructionEq exec
-- |Calculates the size of the exec stack and pushes the result to the int stack.
instructionExecStackDepth :: State -> State
instructionExecStackDepth = instructionStackDepth exec
-- |Moves an item from deep within the exec stack to the top of the exec stack based on
-- the top int from the int stack.
instructionExecYank :: State -> State
instructionExecYank = instructionYank exec
-- |Copies an item from deep within the exec stack to the top of the exec stack based on
-- the top int from the int stack.
instructionExecYankDup :: State -> State
instructionExecYankDup = instructionYankDup exec
-- |Moves an item from the top of the shove stack to deep within the shove stack based on
-- the top int from the int stack.
instructionExecShove :: State -> State
instructionExecShove = instructionShove exec
-- |Copies an item from the top of the shove stack to deep within the shove stack based on
-- the top int from the int stack.
instructionExecShoveDup :: State -> State
instructionExecShoveDup = instructionShoveDup exec
-- |If the code stack is empty, pushes True to bool stack, else False.
instructionExecIsStackEmpty :: State -> State
instructionExecIsStackEmpty = instructionIsStackEmpty exec
-- |Evaluates the top item on the exec stack for each step along the range i to j. Both i and j are
-- taken from the int stack. Differs from code_do_range only in the source of the code and the recursive call.
instructionExecDoRange :: State -> State
instructionExecDoRange state@(State {_exec = e1 : es, _int = i0 : i1 : is}) =
if increment (fromIntegral i0) (fromIntegral i1) /= 0
then state {_exec = e1 : Block [GeneInt (i1 + toInteger (increment (fromIntegral i0) (fromIntegral i1))), GeneInt i0, StateFunc (instructionExecDoRange, "instructionExecDoRange"), e1] : es, _int = i1 : is}
else state {_exec = e1 : es, _int = i1 : is}
where
increment :: Int -> Int -> Int
increment destIdx currentIdx
| currentIdx < destIdx = 1
| currentIdx > destIdx = -1
| otherwise = 0
instructionExecDoRange state = state
-- |Evaluates the top item on the exec stack n times, where n comes from the n comes from the top
-- of the int stack. Differs from code.do*count only in the source of the code and the recursive call.
instructionExecDoCount :: State -> State
instructionExecDoCount state@(State {_exec = e1 : es, _int = i1 : is}) =
if i1 < 1
then state
else state {_exec = Block [GeneInt 0, GeneInt $ i1 - 1, StateFunc (instructionExecDoRange, "instructionExecDoRange"), e1] : es, _int = is}
instructionExecDoCount state = state
-- |Evaluates the top item on the code stack n times, where n comes from the n comes from the top of the int stack.
instructionExecDoTimes :: State -> State
instructionExecDoTimes state@(State {_exec = e1 : es, _int = i1 : is}) =
if i1 < 1
then state
else state {_exec = Block [GeneInt 0, GeneInt $ i1 - 1, StateFunc (instructionExecDoRange, "instructionExecDoRange"), Block [StateFunc (instructionIntPop, "instructionIntPop"), e1]] : es, _int = is}
instructionExecDoTimes state = state
-- |Utility: A shorthand for instructionExecWhile
execWhile :: Gene
execWhile = StateFunc (instructionExecWhile, "instructionExecWhile")
-- |Evaluates the top item on the exec stack repeated until the top bool is no longer True.
instructionExecWhile :: State -> State
instructionExecWhile state@(State {_exec = _ : es, _bool = []}) =
state {_exec = es}
instructionExecWhile state@(State {_exec = alles@(e1 : es), _bool = b1 : bs}) =
if b1
then state {_exec = e1 : execWhile : alles, _bool = bs}
else state {_exec = es}
instructionExecWhile state = state
-- |Evaluates the top item on the exec stack repeated until the top bool is no longer True.
-- Executes at least once.
instructionExecDoWhile :: State -> State
instructionExecDoWhile state@(State {_exec = alles@(e1 : _)}) =
state {_exec = e1 : execWhile : alles}
instructionExecDoWhile state = state
-- |Pops the next item on the exec stack without evaluating it
-- if the top bool is False. Otherwise, has no effect.
-- Eats the top bool no matter what.
instructionExecWhen :: State -> State
instructionExecWhen state@(State {_exec = _ : es, _bool = b1 : bs}) =
if not b1
then state {_exec = es, _bool = bs}
else state {_bool = bs}
instructionExecWhen state = state
-- |The K combinator. Deletes the second to top exec item.
instructionExecK :: State -> State
instructionExecK state@(State {_exec = e1 : _ : es}) = state{_exec = e1 : es}
instructionExecK state = state
-- |The S combinator. Takes the top three top exec items, pushes a Block of the second and third instruction,
-- then the third instruction, and then the first instruction.
instructionExecS :: State -> State
instructionExecS state@(State {_exec = e1 : e2 : e3 : es}) = state{_exec = e1 : e3 : Block [e2, e3] : es}
instructionExecS state = state
-- |The Y combinator. Takes the top exec item. Pushes a Block containing the Y combinator instruction and the top exec item.
-- Then pushes that top exec item again.
instructionExecY :: State -> State
instructionExecY state@(State {_exec = e1 : es}) = state{_exec = e1 : Block [StateFunc (instructionExecY, "instructionExecY"), e1] : es}
instructionExecY state = state
-- |Duplicates the top N items of the exec stack based on the top of the int stack.
instructionExecDupItems :: State -> State
instructionExecDupItems = instructionDupItems exec
allExecInstructions :: [Gene]
allExecInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,228 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.FloatInstructions where
import Data.Fixed (mod')
import HushGP.Instructions.GenericInstructions
import HushGP.Instructions.Utility
import HushGP.State
import Data.Char
import HushGP.TH
-- |Converts the top int to a float and pushes the result to the float stack.
instructionFloatFromInt :: State -> State
instructionFloatFromInt state@(State {_float = fs, _int = i1 : is}) = state {_float = (fromIntegral i1 :: Double) : fs, _int = is}
instructionFloatFromInt state = state
-- |If the top bool True, pushes 1.0 to the float stack. Pushes 0.0 if False.
instructionFloatFromBool :: State -> State
instructionFloatFromBool state@(State {_bool = b1 : bs, _float = fs}) = state {_bool = bs, _float = (if b1 then 1.0 else 0.0) : fs}
instructionFloatFromBool state = state
-- |Takes the top char and converts it to int representation. That int then gets casted to a float and pushed to the float stack.
instructionFloatFromChar :: State -> State
instructionFloatFromChar state@(State {_char = c1 : cs, _float = fs}) = state {_char = cs, _float = (fromIntegral (ord c1) :: Double) : fs}
instructionFloatFromChar state = state
-- |Reads the top string and converts it to a float if possible. If not, acts as a NoOp.
instructionFloatFromString :: State -> State
instructionFloatFromString state@(State {_string = s1 : ss, _float = fs}) =
if all (\x -> isDigit x || x == '.') s1 && amtOccurences "." s1 <= 1
then state{_string = ss, _float = read @Double s1 : fs}
else state
instructionFloatFromString state = state
-- |Adds the top two floats from the float stack.
instructionFloatAdd :: State -> State
instructionFloatAdd state@(State {_float = f1 : f2 : fs}) = state {_float = f2 + f1 : fs}
instructionFloatAdd state = state
-- |Subtracts the first float from the second float on the float stack.
instructionFloatSub :: State -> State
instructionFloatSub state@(State {_float = f1 : f2 : fs}) = state {_float = f2 - f1 : fs}
instructionFloatSub state = state
-- |Subtracts the second float from the first float and pushes the result to the float stack.
instructionFloatSubOpp :: State -> State
instructionFloatSubOpp state@(State {_float = i1 : i2 : is}) = state {_float = i1 - i2 : is}
instructionFloatSubOpp state = state
-- |Multiplies the top two floats on the float stack.
instructionFloatMul :: State -> State
instructionFloatMul state@(State {_float = f1 : f2 : fs}) = state {_float = f2 * f1 : fs}
instructionFloatMul state = state
-- |Divides the first float from the second float on the float stack.
instructionFloatDiv :: State -> State
instructionFloatDiv state@(State {_float = f1 : f2 : fs}) = state {_float = if f1 /= 0 then f2 / f1 : fs else f1 : f2 : fs}
instructionFloatDiv state = state
-- |Divides the second float from the first float and pushes the result to the float stack.
-- This does truncate.
instructionFloatDivOpp :: State -> State
instructionFloatDivOpp state@(State {_float = i1 : i2 : is}) = state {_float = if i2 /= 0 then (i1 / i2) : is else i1 : i2 : is}
instructionFloatDivOpp state = state
-- |Mods the first float from the second float on the float stack.
instructionFloatMod :: State -> State
instructionFloatMod state@(State {_float = f1 : f2 : fs}) = state {_float = if f1 /= 0 then f2 `mod'` f1 : fs else f1 : f2 : fs}
instructionFloatMod state = state
-- |Mods the second float from the first float and pushes the result to the float stack.
-- This does truncate.
instructionFloatModOpp :: State -> State
instructionFloatModOpp state@(State {_float = f1 : f2 : fs}) = state {_float = if f2 /= 0 then (f1 `mod'` f2) : fs else f1 : f2 : fs}
instructionFloatModOpp state = state
-- |Takes the top two floats from the float stack and pushes the minimum of the two back on top.
instructionFloatMin :: State -> State
instructionFloatMin state@(State {_float = f1 : f2 : fs}) = state {_float = min f1 f2 : fs}
instructionFloatMin state = state
-- |Takes the top two floats from the float stack and pushes the maximum of the two back on top.
instructionFloatMax :: State -> State
instructionFloatMax state@(State {_float = f1 : f2 : fs}) = state {_float = max f1 f2 : fs}
instructionFloatMax state = state
-- |Adds one to the top float from the float stack.
instructionFloatInc :: State -> State
instructionFloatInc state@(State {_float = f1 : fs}) = state {_float = f1 + 1 : fs}
instructionFloatInc state = state
-- |Subtracts one from the top float from the float stack.
instructionFloatDec :: State -> State
instructionFloatDec state@(State {_float = f1 : fs}) = state {_float = f1 - 1 : fs}
instructionFloatDec state = state
-- |Takes the top two floats from the float stack and pushes the result of: the top float item < the second float item
instructionFloatLT :: State -> State
instructionFloatLT state@(State {_float = f1 : f2 : fs, _bool = bs}) = state {_float = fs, _bool = (f1 < f2) : bs}
instructionFloatLT state = state
-- |Takes the top two floats from the float stack and pushes the result of: the top float item > the second float item
instructionFloatGT :: State -> State
instructionFloatGT state@(State {_float = f1 : f2 : fs, _bool = bs}) = state {_float = fs, _bool = (f1 > f2) : bs}
instructionFloatGT state = state
-- |Takes the top two floats from the float stack and pushes the result of: the top float item <= the second float item
instructionFloatLTE :: State -> State
instructionFloatLTE state@(State {_float = f1 : f2 : fs, _bool = bs}) = state {_float = fs, _bool = (f1 <= f2) : bs}
instructionFloatLTE state = state
-- |Takes the top two floats from the float stack and pushes the result of: the top float item >= the second float item
instructionFloatGTE :: State -> State
instructionFloatGTE state@(State {_float = f1 : f2 : fs, _bool = bs}) = state {_float = fs, _bool = (f1 >= f2) : bs}
instructionFloatGTE state = state
-- |Pops the top float from the float stack.
instructionFloatPop :: State -> State
instructionFloatPop = instructionPop float
-- |Duplicates the top float on the float stack.
instructionFloatDup :: State -> State
instructionFloatDup = instructionDup float
-- |Duplicates the top float on the float stack N times based off the top of the int stack.
instructionFloatDupN :: State -> State
instructionFloatDupN = instructionDupN float
-- |Swaps the top two floats on the float stack.
instructionFloatSwap :: State -> State
instructionFloatSwap = instructionSwap float
-- |Rotates the top three floats on the float stack.
instructionFloatRot :: State -> State
instructionFloatRot = instructionRot float
-- |Sets the float stack to []
instructionFloatFlush :: State -> State
instructionFloatFlush = instructionFlush float
-- |Checks if the top two floats are equal. Pushes the result to the bool stack.
-- Might override this later to check for equality in a range rather than exact equality.
instructionFloatEq :: State -> State
instructionFloatEq = instructionEq float
-- |Pushes the depth of the stack to the int stack.
instructionFloatStackDepth :: State -> State
instructionFloatStackDepth = instructionStackDepth float
-- |Copies an item from deep within the float stack to the top of the float stack based on
-- the top int from the int stack.
instructionFloatYankDup :: State -> State
instructionFloatYankDup = instructionYankDup float
-- |Moves an item from deep within the float stack to the top of the float stack based on
-- the top int from the int stack.
instructionFloatYank :: State -> State
instructionFloatYank = instructionYank float
-- |Copies an item from the top of the float stack to deep within the float stack based on
-- the top int from the int stack.
instructionFloatShoveDup :: State -> State
instructionFloatShoveDup = instructionShoveDup float
-- |Moves an item from the top of the float stack to deep within the float stack based on
-- the top int from the int stack.
instructionFloatShove :: State -> State
instructionFloatShove = instructionShove float
-- |Pushes True to the bool stack if the float stack is empty. False if not.
instructionFloatIsStackEmpty :: State -> State
instructionFloatIsStackEmpty = instructionIsStackEmpty float
-- |Duplicate the top N items from the float stack based on the top int from the int stack.
instructionFloatDupItems :: State -> State
instructionFloatDupItems = instructionDupItems float
-- |Pushes the sin of the top float to the float stack.
instructionFloatSin :: State -> State
instructionFloatSin state@(State {_float = f1 : fs}) = state {_float = sin f1 : fs}
instructionFloatSin state = state
-- |Pushes the cos of the top float to the float stack.
instructionFloatCos :: State -> State
instructionFloatCos state@(State {_float = f1 : fs}) = state {_float = cos f1 : fs}
instructionFloatCos state = state
-- |Pushes the tan of the top float to the float stack.
instructionFloatTan :: State -> State
instructionFloatTan state@(State {_float = f1 : fs}) = state {_float = tan f1 : fs}
instructionFloatTan state = state
-- |Pushes the absolute value of the top float to the float stack.
instructionFloatAbs :: State -> State
instructionFloatAbs state@(State {_float = f1 : fs}) = state {_float = abs f1 : fs}
instructionFloatAbs state = state
-- |Pushes the exponential of the top float to the float stack.
instructionFloatExp :: State -> State
instructionFloatExp state@(State {_float = f1 : fs}) = state {_float = exp f1 : fs}
instructionFloatExp state = state
-- |Pushes the log of the top float to the float stack.
instructionFloatLog :: State -> State
instructionFloatLog state@(State {_float = f1 : fs}) = state {_float = log f1 : fs}
instructionFloatLog state = state
-- |Pushes the squared value of the top float to the float stack.
instructionFloatSquare :: State -> State
instructionFloatSquare state@(State {_float = f1 : fs}) = state {_float = f1 ^ (2 :: Int) : fs}
instructionFloatSquare state = state
-- |Pushes the cubed value of the top float to the float stack.
instructionFloatCube :: State -> State
instructionFloatCube state@(State {_float = f1 : fs}) = state {_float = f1 ^ (3 :: Int) : fs}
instructionFloatCube state = state
-- |Pushes the square rooted value of the top float to the float stack.
instructionFloatSqrt :: State -> State
instructionFloatSqrt state@(State {_float = f1 : fs}) = state {_float = sqrt f1 : fs}
instructionFloatSqrt state = state
-- |Pushes the top float with its sign reversed to the top of the float stack.
instructionFloatReverseSign :: State -> State
instructionFloatReverseSign state@(State {_float = f1 : fs}) = state {_float = (-1) * f1 : fs}
instructionFloatReverseSign state = state
allFloatInstructions :: [Gene]
allFloatInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,588 @@
module HushGP.Instructions.GenericInstructions where
import Control.Lens
import Data.List (sort, sortBy)
import Data.Ord
import Data.List.Split
import HushGP.State
import HushGP.Instructions.Utility-- import Debug.Trace
-- |Does No Operation. Useful for genome stuff :)
instructionNoOpBlock :: State -> State
instructionNoOpBlock state = state
-- |Does No Operation. Just evolve fodder.
instructionNoOp :: State -> State
instructionNoOp state = state
-- |Duplicates the top of a stack based on a lens.
instructionDup :: Lens' State [a] -> State -> State
instructionDup accessor state =
case uncons (view accessor state) of
Nothing -> state
Just (x1,_) -> state & accessor .~ x1 : view accessor state
-- |Pops the top of the stack based on a lens.
instructionPop :: Lens' State [a] -> State -> State
instructionPop accessor state = state & accessor .~ drop 1 (view accessor state)
-- |Pushes True if the lens' stack is empty, False if not.
instructionIsStackEmpty :: Lens' State [a] -> State -> State
instructionIsStackEmpty accessor state@(State {_bool = bs}) = state{_bool = null (view accessor state) : bs}
-- |Duplicates the top of a stack based on a lens and the top of the int stack.
instructionDupN :: forall a. Lens' State [a] -> State -> State
instructionDupN accessor state =
case uncons (view int state) of
Just (i1,is) ->
case uncons (view accessor state{_int = is}) of
Just (a1,as) ->
instructionDupNHelper i1 a1 accessor (state{_int = is} & accessor .~ as)
_ -> state
_ -> state
where
instructionDupNHelper :: Integral b => b -> a -> Lens' State [a] -> State -> State
instructionDupNHelper count instruction internalAccessor internalState =
if count > 0
then instructionDupNHelper (count - 1) instruction internalAccessor (internalState & accessor .~ (instruction : view accessor internalState))
else internalState
-- |Duplicates the top N items on a stack. If n <= 0, nothing happens
-- TODO: Will need to implement a max stack items at some point
instructionDupItems :: Lens' State [a] -> State -> State
instructionDupItems accessor state@(State {_int = i1 : is}) =
if i1 <= 0
then state{_int = is}
else state{_int = is} & accessor .~ (take (fromIntegral i1) (view accessor state{_int = is}) <> view accessor state{_int = is})
instructionDupItems _ state = state
-- |Swaps the top two instructions based on a lens
instructionSwap :: Lens' State [a] -> State -> State
instructionSwap accessor state =
state & accessor .~ swapper (view accessor state)
where
swapper :: [a] -> [a]
swapper (x1 : x2 : xs) = x2 : x1 : xs
swapper xs = xs
-- |Rotates top 3 integers based on a lens.
-- We could use template haskell to rotate any number of these as
-- an instruction later.
instructionRot :: Lens' State [a] -> State -> State
instructionRot accessor state =
state & accessor .~ rotator (view accessor state)
where
rotator :: [a] -> [a]
rotator (x1 : x2 : x3 : xs) = x3 : x1 : x2 : xs
rotator xs = xs
-- |Deletes all instructions in a stack based on a lens.
instructionFlush :: Lens' State [a] -> State -> State
instructionFlush accessor state = state & accessor .~ []
-- |Checks if the two top instructions are equal based on a lens.
-- Pushes the result to the bool stack.
instructionEq :: forall a. Eq a => Lens' State [a] -> State -> State
instructionEq accessor state =
case uncons $ view accessor state of
Nothing -> state
Just (x1, x2 : _) -> droppedState & bool .~ (x1 == x2) : view bool droppedState
Just _ -> state
where
droppedState :: State
droppedState = state & accessor .~ drop 2 (view accessor state)
-- |Calculates the stack depth based on a lens and pushes the result to the int stackk.
instructionStackDepth :: Lens' State [a] -> State -> State
instructionStackDepth accessor state@(State {_int = is}) = state{_int = toInteger (length (view accessor state)) : is}
-- |Copies an item from deep within a lens' stack to the top of the lens' stack based on
-- the top int from the int stack.
instructionYankDup :: Lens' State [a] -> State -> State
instructionYankDup accessor state@(State {_int = i1 : is}) =
if notEmptyStack accessor state{_int = is}
then state{_int = is} & accessor .~ (view accessor state{_int = is} !! max 0 (min (fromIntegral i1) (length (view accessor state{_int = is}) - 1))) : view accessor state{_int = is}
else state
instructionYankDup _ state = state
-- |Moves an item from deep within a lens' stack to the top of the lens' stack based on
-- the top int from the int stack.
instructionYank :: forall a. Lens' State [a] -> State -> State
instructionYank accessor state@(State {_int = i1 : is}) =
let
myIndex :: Int
myIndex = max 0 (min (fromIntegral i1) (length (view accessor state{_int = is}) - 1))
item :: a
item = view accessor state{_int = is} !! myIndex
deletedState :: State
deletedState = state{_int = is} & accessor .~ deleteAt myIndex (view accessor state{_int = is})
in
if notEmptyStack accessor state{_int = is} then deletedState & accessor .~ item : view accessor deletedState else state
instructionYank _ state = state
-- |Copies an item from the top of a lens' stack to deep within the lens' stack based on
-- the top int from the int stack.
-- In pysh, instructionShoveDup and instructionShove behave differently when indexing in such a way that
-- the duplicated index matters whether or not it's present in the stack at the moment of calculation.
-- I'm not going to keep this behavior. Check out interpysh examples for how pysh handles it.
instructionShoveDup :: Lens' State [a] -> State -> State
instructionShoveDup accessor state@(State {_int = i1 : is}) =
case uncons (view accessor state{_int = is}) of
Just (x,_) -> state{_int = is} & accessor .~ combineTuple x (splitAt (max 0 (min (fromIntegral i1) (length (view accessor state{_int = is}) - 1))) (view accessor state{_int = is}))
_ -> state
instructionShoveDup _ state = state
-- |Moves an item from the top of a lens' stack to deep within the lens' stack based on
-- the top int from the int stack.
instructionShove :: Lens' State [a] -> State -> State
instructionShove accessor state = state & accessor .~ drop 1 (view accessor (instructionShoveDup accessor state ))
-- |Concats two semigroupable items together based on a lens. Not char generic.
instructionVectorConcat :: Semigroup a => Lens' State [a] -> State -> State
instructionVectorConcat accessor state =
case uncons (view accessor state) of
Just (x1, x2:_) -> droppedState & accessor .~ (x1 <> x2) : view accessor droppedState
_ -> state
where
droppedState :: State
droppedState = state & accessor .~ drop 2 (view accessor state)
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- takes the top item of the primitive stack and prepends it to the first vector in
-- the vector stack if there is one.
instructionVectorConj :: Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorConj primAccessor vectorAccessor state =
case (uncons (view primAccessor state), uncons (view vectorAccessor state)) of
(Just (p1,ps), Just (v1,vs)) -> state & primAccessor .~ ps & vectorAccessor .~ ((p1 : v1) : vs)
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- takes the top item of the primitive stack and appends it to the first vector in
-- the vector stack if there is one.
instructionVectorConjEnd :: Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorConjEnd primAccessor vectorAccessor state =
case (uncons (view primAccessor state), uncons (view vectorAccessor state)) of
(Just (p1,ps), Just (v1,vs)) -> state & primAccessor .~ ps & vectorAccessor .~ ((v1 <> [p1]) : vs)
_ -> state
-- |Takes the first N items from the first vector on the top of a vector stack and
-- pushes the result to said vector stack.
instructionVectorTakeN :: Lens' State [[a]] -> State -> State
instructionVectorTakeN accessor state@(State {_int = i1 : is}) =
case uncons (view accessor state) of
Just (v1, vs) -> state{_int = is} & accessor .~ (take (absNum i1 v1) v1 : vs)
_ -> state
instructionVectorTakeN _ state = state
-- |Takes the last N items from the first vector on the top of a vector stack and
-- pushes the result to said vector stack.
instructionVectorTakeRN :: Lens' State [[a]] -> State -> State
instructionVectorTakeRN accessor state@(State {_int = i1 : is}) =
case uncons (view accessor state) of
Just (v1, vs) -> state{_int = is} & accessor .~ (takeR (absNum i1 v1) v1 : vs)
_ -> state
instructionVectorTakeRN _ state = state
-- |Takes the sublist of the top vector based on a passed lens. Check out the
-- subList documentation for information on how this works.
instructionSubVector :: Lens' State [[a]] -> State -> State
instructionSubVector accessor state@(State {_int = i1 : i2 : is}) =
case uncons (view accessor state) of
Just (v1, vs) -> state{_int = is} & accessor .~ (subList (fromIntegral i1) (fromIntegral i2) v1 : vs)
_ -> state
instructionSubVector _ state = state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- Takes the first item from the top vector and places it onto the passed primitive stack.
instructionVectorFirst :: Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorFirst primAccessor vectorAccessor state =
case uncons (view vectorAccessor state) of
Just (v1, vs) ->
case uncons v1 of
Just (vp1, _) -> state & primAccessor .~ (vp1 : view primAccessor state) & vectorAccessor .~ vs
_ -> state
_ -> state
-- |Based on a vector lens, takes the first item from the top vector on the vector stack
-- and creates a vector wrapping that first item, pushing it back onto the stack.
-- Not to be confused with instructionVectorFromFirstPrim.
instructionVectorFromFirstPrim :: Lens' State [[a]] -> State -> State
instructionVectorFromFirstPrim accessor state =
case uncons (view accessor state) of
Just (v1, vs) ->
case uncons v1 of
Just (vp1, _) -> state & accessor .~ ([vp1] : vs)
_ -> state
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- pushes the top item of the primitive stack wrapped in a list to the top of the
-- vector stack. Not to be confused with instructionVectorFromFirstPrim.
instructionVectorFromPrim :: Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorFromPrim primAccessor vectorAccessor state =
case uncons (view primAccessor state) of
Just (p1, ps) -> state & primAccessor .~ ps & vectorAccessor .~ ([p1] : view vectorAccessor state)
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- Takes the last item from the top vector and places it onto the passed primitive stack.
instructionVectorLast :: Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorLast primAccessor vectorAccessor state =
case uncons (view vectorAccessor state) of
Just (v1, vs) ->
case uncons (drop (length v1 - 1) v1) of -- gonna keep this implementation over using last as this can't error
Just (vplast, _) -> state & primAccessor .~ (vplast : view primAccessor state) & vectorAccessor .~ vs
_ -> state
_ -> state
-- |Based on a vector lens, takes the last item from the top vector on the vector stack
-- and creates a vector wrapping that last item, pushing it back onto the stack.
instructionVectorFromLastPrim :: Lens' State [[a]] -> State -> State
instructionVectorFromLastPrim accessor state =
case uncons (view accessor state) of
Just (v1, vs) ->
case uncons (drop (length v1 - 1) v1) of
Just (vp1, _) -> state & accessor .~ ([vp1] : vs)
_ -> state
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- Takes the Nth item from the top vector and places it onto the passed primitive stack
-- based on an int from the int stack.
instructionVectorNth :: Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorNth primAccessor vectorAccessor state@(State {_int = i1 : is}) =
case uncons (view vectorAccessor state) of
Just (v1, vs) -> state{_int = is} & primAccessor .~ (v1 !! absNum i1 v1 : view primAccessor state{_int = is}) & vectorAccessor .~ vs
_ -> state
instructionVectorNth _ _ state= state
-- |Based on a vector lens, takes the Nth item from the top vector on the vector stack
-- and creates a vector wrapping that Nth item, pushing it back onto the stack. N is
-- the top item on the int stack.
instructionVectorFromNthPrim :: Lens' State [[a]] -> State -> State
instructionVectorFromNthPrim accessor state@(State {_int = i1 : is}) =
case uncons (view accessor state) of
Just (v1, vs) -> state{_int = is} & accessor .~ ([v1 !! absNum i1 v1] : vs)
_ -> state
instructionVectorFromNthPrim _ state = state
-- |Takes the top vector, removes the first item of said vector, and pushes the result back to top
-- of the stack, based on a lens.
instructionVectorRest :: Lens' State [[a]] -> State -> State
instructionVectorRest accessor state =
case uncons (view accessor state) of
Just (v1, vs) -> state & accessor .~ (drop 1 v1 : vs)
_ -> state
-- |Takes the top vector, removes the last item of said vector, and pushes the result back to top
-- of the stack, based on a vector lens.
instructionVectorButLast :: Lens' State [[a]] -> State -> State
instructionVectorButLast accessor state =
case uncons (view accessor state) of
Just (v1, vs) -> state & accessor .~ (safeInit v1 : vs)
_ -> state
-- |Based on a vector lens, drops the first N items from the top vector.
-- Pushes the result back to the vector stack. N is pulled from the top
-- of the int stack.
instructionVectorDrop :: Lens' State [[a]] -> State -> State
instructionVectorDrop accessor state@(State {_int = i1 : is}) =
case uncons (view accessor state{_int = is}) of
Just (v1, vs) -> state{_int = is} & accessor .~ (drop (absNum i1 v1) v1 : vs)
_ -> state
instructionVectorDrop _ state = state
-- |Based on a vector lens, drops the last N items from the top vector.
-- Pushes the result back to the vector stack. N is pulled from the top
-- of the int stack.
instructionVectorDropR :: Lens' State [[a]] -> State -> State
instructionVectorDropR accessor state@(State {_int = i1 : is}) =
case uncons (view accessor state{_int = is}) of
Just (v1, vs) -> state{_int = is} & accessor .~ (dropR (absNum i1 v1) v1 : vs)
_ -> state
instructionVectorDropR _ state = state
-- |Takes the top vector, pushes the length of that vector to the int stack, based on a vector lens.
instructionLength :: Lens' State [[a]] -> State -> State
instructionLength accessor state@(State {_int = is}) =
case uncons (view accessor state) of
Just (v1, vs) -> state{_int = toInteger (length v1) : is} & accessor .~ vs
_ -> state
-- |Takes the top vector, reverses it, based on a lens.
instructionReverse :: Lens' State [[a]] -> State -> State
instructionReverse accessor state =
case uncons (view accessor state) of
Just (v1, vs) -> state & accessor .~ (reverse v1 : vs)
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- takes the vector and individually pushes its indices to the passed primitive stack.
instructionPushAll :: Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionPushAll primAccessor vectorAccessor state =
case uncons (view vectorAccessor state) of
Just (v1, vs) -> state & vectorAccessor .~ vs & primAccessor .~ (v1 <> view primAccessor state)
_ -> state
-- |Based on a vector lens, makes an empty vector and pushes it to the passed stack.
instructionVectorMakeEmpty :: Lens' State [[a]] -> State -> State
instructionVectorMakeEmpty accessor state = state & accessor .~ ([] : view accessor state)
-- |Based on a vector lens, checks if the top vector is empty. If so, pushes True to the
-- bool stack. If not, pushes False.
instructionVectorIsEmpty :: Lens' State [[a]] -> State -> State
instructionVectorIsEmpty accessor state@(State {_bool = bs}) =
case uncons (view accessor state) of
Just (v1, vs) -> state{_bool = null v1 : bs} & accessor .~ vs
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- If the vector on the top of the vector stack contains the top item on the primitive stack,
-- pushes True to the bool stack. Pushes False otherwise.
instructionVectorContains :: Eq a => Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorContains primAccessor vectorAccessor state@(State {_bool = bs}) =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, ps)) -> state{_bool = (findSubA v1 [p1] /= -1) : bs} & vectorAccessor .~ vs & primAccessor .~ ps
_ -> state
-- |Based on a vector lens and the two vectors on the top of said stack.
-- If the second vector can be found within the first vector, True is pushed to the
-- bool stack. If not, False is pushed to the bool stack.
instructionVectorContainsVector :: Eq a => Lens' State [[a]] -> State -> State
instructionVectorContainsVector accessor state@(State {_bool = bs}) =
case uncons (view accessor state) of
Just (v1, v2 : vs) -> state & accessor .~ vs & bool .~ ((findSubA v1 v2 /= (-1)) : bs)
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- finds the first index of the top item in the primitive stack inside of the
-- top vector from the vector stack and pushes the result to the int stack.
instructionVectorIndexOf :: Eq a => Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorIndexOf primAccessor vectorAccessor state =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, ps)) -> (state & vectorAccessor .~ vs & primAccessor .~ ps) & int .~ (toInteger (findSubA v1 [p1]) : view int (state & vectorAccessor .~ vs & primAccessor .~ ps))
_ -> state
-- |Based on a vector lens and the two vectors on top of said stack. Searches and pushes the
-- index of the second vector inside of the first vector to the int stack. Pushes -1 if not found.
instructionVectorIndexOfVector :: Eq a => Lens' State [[a]] -> State -> State
instructionVectorIndexOfVector accessor state@(State {_int = is}) =
case uncons (view accessor state) of
Just (v1, v2 : vs) -> state & accessor .~ vs & int .~ (toInteger (findSubA v1 v2) : is)
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- finds the amount of times the top item in the primitive stack occurs inside of the
-- top vector from the vector stack and pushes the result to the int stack.
instructionVectorOccurrencesOf :: Eq a => Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorOccurrencesOf primAccessor vectorAccessor state =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, ps)) -> (state & vectorAccessor .~ vs & primAccessor .~ ps) & int .~ (toInteger (amtOccurences v1 [p1]) : view int (state & vectorAccessor .~ vs & primAccessor .~ ps))
_ -> state
-- |Based on a vector lens and the top two vectors in said stack,
-- Counts the amount of occurrences of the second vector in the first
-- vector. Pushes the result to the string stack.
instructionVectorOccurrencesOfVector :: Eq a => Lens' State [[a]] -> State -> State
instructionVectorOccurrencesOfVector accessor state@(State {_int = is}) =
case uncons (view accessor state) of
Just (v1, v2 : vs) -> state & accessor .~ vs & int .~ (toInteger (amtOccurences v1 v2) : is)
_ -> state
-- |This function parses the primitives inside a vector type and pushes that vector split into
-- lists of size one and pushes the result onto the respective vector stack. Based on a vector lens.
instructionVectorParseToPrim :: Lens' State [[a]] -> State -> State
instructionVectorParseToPrim accessor state =
case uncons (view accessor state) of
Just (x1, xs) -> state & accessor .~ (chunksOf 1 x1 <> xs)
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type.
-- Sets the Nth index inside of the top vector from the vector stack to the top value
-- from the primitive stack. N is based on an int from the top of the int stack.
instructionVectorSetNth :: Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorSetNth primAccessor vectorAccessor state@(State {_int = i1 : is}) =
case (uncons (view vectorAccessor state{_int = is}), uncons (view primAccessor state{_int = is})) of
(Just (v1, vs), Just (p1, ps)) -> state{_int = is} & vectorAccessor .~ (replaceAt (absNum i1 v1) p1 v1 : vs) & primAccessor .~ ps
_ -> state
instructionVectorSetNth _ _ state = state
-- |Based on two lenses, one of a primitive type and the next of a vector type.
-- Splits the vector on top of the vector stack with the top primitive and pushes the
-- result to the original vector stack.
instructionVectorSplitOn :: Eq a => Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorSplitOn primAccessor vectorAccessor state =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, ps)) -> state & primAccessor .~ ps & vectorAccessor .~ (reverse (splitOn [p1] v1) <> vs)
_ -> state
-- |Based on a vector lens and top two items of said stack, splits the
-- first vector based on the second vector and pushes the result to the
-- original vector stack.
instructionVectorSplitOnVector :: Eq a => Lens' State [[a]] -> State -> State
instructionVectorSplitOnVector accessor state =
case uncons (view accessor state) of
Just (v1, v2 : vs) -> state & accessor .~ (reverse (splitOn v2 v1) <> vs)
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- replaces Maybe Int occurrences inside of the top vector from the vector stack with two values from
-- the primitive stack. The top of the primitive stack is the old value to be replaced. The second item
-- in the primitive stack is the new value to replace the old one. Nothing replaces all occurrences.
instructionVectorReplace :: Eq a => Lens' State [a] -> Lens' State [[a]] -> Maybe Int -> State -> State
instructionVectorReplace primAccessor vectorAccessor amt state =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, p2 : ps)) -> state & vectorAccessor .~ (replace v1 [p1] [p2] amt: vs) & primAccessor .~ ps
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- replaces N occurrences inside of the top vector from the vector stack with two values from
-- the primitive stack. The top of the primitive stack is the old value to be replaced. The second item
-- in the primitive stack is the new value to replace the old one. N is pulled from the top of the int stack.
instructionVectorReplaceN :: Eq a => Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorReplaceN primAccessor vectorAccessor state@(State {_int = i1 : is}) = instructionVectorReplace primAccessor vectorAccessor (Just (fromIntegral i1)) state{_int = is}
instructionVectorReplaceN _ _ state = state
-- |Based on a vector lens and the top three vectors on said stack.
-- Inside of the first vector, replaces the number of instances specified
-- by the Maybe Int parameter of the second vector with the third vector.
-- If amt is Nothing, replaces all instances.
instructionVectorReplaceVector :: Eq a => Lens' State [[a]] -> Maybe Int -> State -> State
instructionVectorReplaceVector accessor amt state =
case uncons (view accessor state) of
Just (v1, v2 : v3 : vs) -> state & accessor .~ (replace v1 v2 v3 amt : vs)
_ -> state
-- |Based on a vector lens, the top three vectors on said stack, and the top int on the int stack.
-- Inside of the first vector, replaces the number of instances specified
-- by the top of the int stack of the second vector with the third vector.
instructionVectorReplaceVectorN :: Eq a => Lens' State [[a]] -> State -> State
instructionVectorReplaceVectorN accessor state@(State {_int = i1 : is}) = instructionVectorReplaceVector accessor (Just (fromIntegral i1)) state{_int = is}
instructionVectorReplaceVectorN _ state = state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- Removes Maybe Int occurrences inside of the top vector from the vector stack where the top
-- item from the primitive stack equals a primitive inside of the vector stack. If Nothing is passed
-- rather than a Just Int, will remove all occurrences.
instructionVectorRemove :: Eq a => Lens' State [a] -> Lens' State [[a]] -> Maybe Int -> State -> State
instructionVectorRemove primAccessor vectorAccessor amt state =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, ps)) -> state & vectorAccessor .~ (replace v1 [p1] [] amt: vs) & primAccessor .~ ps
_ -> state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- Removes N occurrences inside of the top vector from the vector stack where the top
-- item from the primitive stack equals a primitive inside of the vector stack. N is pulled
-- from the top of the int stack. Not to be confused with instructionVectorRemoveNth.
instructionVectorRemoveN :: Eq a => Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorRemoveN primAccessor vectorAccessor state@(State {_int = i1 : is}) = instructionVectorRemove primAccessor vectorAccessor (Just (fromIntegral i1)) state{_int = is}
instructionVectorRemoveN _ _ state = state
-- |Based on a vector lens. Removes the Nth index of the top vector of the passed
-- vector stack. N is pulled from the top of the int stack. Not to be confused with
-- instructionVectorRemoveN.
instructionVectorRemoveNth :: Lens' State [[a]] -> State -> State
instructionVectorRemoveNth accessor state@(State {_int = i1 : is}) =
case uncons (view accessor state{_int = is}) of
Just (v1, vs) -> state{_int = is} & accessor .~ (deleteAt (absNum i1 v1) v1 : vs)
_ -> state
instructionVectorRemoveNth _ state = state
-- |Based on a vector lens and the two vectors on top of said stack.
-- Inside of the first vector, removes the number of instances specified
-- by the Maybe Int parameter of the second vector. Nothing removes all instances.
instructionVectorRemoveVector :: Eq a => Lens' State [[a]] -> Maybe Int -> State -> State
instructionVectorRemoveVector accessor amt state =
case uncons (view accessor state) of
Just (v1, v2 : vs) -> state & accessor .~ (replace v1 v2 [] amt : vs)
_ -> state
-- |Based on a vector lens, the top two vectors on said stack, and the top int on the int stack.
-- Inside of the first vector, removes the number of instances specified
-- by the top of the int stack of the second vector.
instructionVectorRemoveVectorN :: Eq a => Lens' State [[a]] -> State -> State
instructionVectorRemoveVectorN accessor state@(State {_int = i1 : is}) = instructionVectorRemoveVector accessor (Just (fromIntegral i1)) state{_int = is}
instructionVectorRemoveVectorN _ state = state
-- |Based on two lenses, one of a primitive type and the next of a vector type,
-- iterates over the top vector from the vector stack using the top code from the code stack.
-- Pysh explains this better.
instructionVectorIterate :: Lens' State [a] -> Lens' State [[a]] -> ([a] -> Gene) -> (State -> State) -> String -> State -> State
instructionVectorIterate primAccessor vectorAccessor vectorType typeIterateFunction typeIterateFunctionName state@(State {_exec = e1 : es}) =
case uncons (view vectorAccessor state) of
Just ([], vs) -> state{_exec = es} & vectorAccessor .~ vs
Just ([x], vs) -> state & primAccessor .~ (x : view primAccessor state) & vectorAccessor .~ vs
Just (v1, vs) ->
(case uncons v1 of
Just (nv1, nvs) -> state{_exec = e1 : vectorType nvs : StateFunc (typeIterateFunction, typeIterateFunctionName) : e1 : es} & primAccessor .~ (nv1 : view primAccessor state) & vectorAccessor .~ vs
_ -> state) -- This should never happen
_ -> state
instructionVectorIterate _ _ _ _ _ state = state
-- |Moves a type from a stack and places it onto the code stack. Based on a primitive stack.
-- The (a -> Gene) is something like GeneBool or GeneInt for example.
instructionCodeFrom :: Lens' State [a] -> (a -> Gene) -> State -> State
instructionCodeFrom accessor geneType state@(State {_code = cs}) =
case uncons (view accessor state) of
Just (x, xs) -> state{_code = geneType x : cs} & accessor .~ xs
_ -> state
-- |Sorts the top vector in a vector stack, based on a vector lens.
instructionVectorSort :: Ord a => Lens' State [[a]] -> State -> State
instructionVectorSort accessor state =
case uncons (view accessor state) of
Just (x, xs) -> state & accessor .~ (sort x : xs)
_ -> state
-- |Sorts the top vector in a vector stack in reverse order for a vectorType, based on a vector lens.
instructionVectorSortReverse :: Ord a => Lens' State [[a]] -> State -> State
instructionVectorSortReverse accessor state =
case uncons (view accessor state) of
Just (x, xs) -> state & accessor .~ (sortBy (comparing Data.Ord.Down) x : xs)
_ -> state
-- |Takes a vector lens, a primitive lens, and the top of the int stack
-- Inserts the top of the primitive stack into a index specified by the
-- top of the int stack into the top vector from the vector stack.
instructionVectorInsert :: Lens' State [a] -> Lens' State [[a]] -> State -> State
instructionVectorInsert primAccessor vectorAccessor state@(State {_int = i1 : is}) =
case (uncons (view vectorAccessor state{_int = is}), uncons (view primAccessor state{_int = is})) of
(Just (v1, vs), Just (p1, ps)) -> state{_int = is} & primAccessor .~ ps & vectorAccessor .~ (combineTuple p1 (splitAt (fromIntegral i1) v1) : vs)
_ -> state
instructionVectorInsert _ _ state = state
-- |Takes a vector lens and inserts the second vector on the vector stack
-- into the first vector on the vector stack based on an int from the
-- int stack.
instructionVectorInsertVector :: Lens' State [[a]] -> State -> State
instructionVectorInsertVector accessor state@(State {_int = i1 : is}) =
case uncons (view accessor state) of
Just (v1, v2 : vs) ->
state{_int = is} & accessor .~ (combineTupleList v2 (splitAt (fromIntegral i1) v1) : vs)
_ -> state
instructionVectorInsertVector _ state = state
-- |Takes a numeric vector lens and a primitive lens. Pushes the mean of the top
-- vector to the primitive stack.
-- instructionVectorMean :: Fractional a => Lens' State [a] -> Lens' State [[a]] -> (b -> a) -> State -> State
-- instructionVectorMean primAccessor vectorAccessor wrangleFunc state =
-- case uncons (view vectorAccessor state) of
-- Just (v1, vs) -> state & vectorAccessor .~ vs & primAccessor .~ (mean v1 : view primAccessor state)
-- _ -> state
-- |Takes a vector lens, a primitive lens, and an arbitrary function. Pushes the result
-- of applying the arbitrary function to the top vector lens item to the top of the primitive lens stack.
instructionVectorFuncVectorToPrim :: Ord a => Lens' State [a] -> Lens' State [[a]] -> ([a] -> a) -> State -> State
instructionVectorFuncVectorToPrim primAccessor vectorAccessor func state =
case uncons (view vectorAccessor state) of
Just (v1, vs) -> state & vectorAccessor .~ vs & primAccessor .~ func v1 : view primAccessor state
_ -> state
-- |Takes a vector lens and an arbitrary function. Applies the arbitrary function to the top
-- item of the vector lens stack and returns it to said stack.
instructionVectorFuncVectorToVector :: Ord a => Lens' State [[a]] -> ([a] -> [a]) -> State -> State
instructionVectorFuncVectorToVector accessor func state =
case uncons (view accessor state) of
Just (v1, vs) -> state & accessor .~ func v1 : vs
_ -> state

View File

@ -0,0 +1,228 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.IntInstructions where
import HushGP.State
import HushGP.Instructions.GenericInstructions
import Data.Char
import HushGP.TH
-- |Converts the top float to an int and pushes the result to the int stack.
instructionIntFromFloat :: State -> State
instructionIntFromFloat state@(State {_float = f1 : fs, _int = is}) = state {_float = fs, _int = floor f1 : is}
instructionIntFromFloat state = state
-- |If the top bool True, pushes 1 to the int stack. Pushes 0 if False.
instructionIntFromBool :: State -> State
instructionIntFromBool state@(State {_bool = b1 : bs, _int = is}) = state {_bool = bs, _int = (if b1 then 1 else 0) : is}
instructionIntFromBool state = state
-- |Takes the top char and converts it to int representation. The result is pushed to the int stack.
instructionIntFromChar :: State -> State
instructionIntFromChar state@(State {_char = c1 : cs, _int = is}) = state {_char = cs, _int = fromIntegral (ord c1) : is}
instructionIntFromChar state = state
-- |Reads the top string and converts it to a int if possible. If not, acts as a NoOp.
instructionIntFromString :: State -> State
instructionIntFromString state@(State {_string = s1 : ss, _int = is}) =
if all isDigit s1
then state{_string = ss, _int = read @Integer s1 : is}
else state
instructionIntFromString state = state
-- |Adds the top two ints from the int stack and pushes the result to the int stack.
instructionIntAdd :: State -> State
instructionIntAdd state@(State {_int = i1 : i2 : is}) = state {_int = i2 + i1 : is}
instructionIntAdd state = state
-- |Subtracts the first int from the second int and pushes the result to the int stack.
instructionIntSub :: State -> State
instructionIntSub state@(State {_int = i1 : i2 : is}) = state {_int = i2 - i1 : is}
instructionIntSub state = state
-- |Subtracts the second int from the first int and pushes the result to the int stack.
instructionIntSubOpp :: State -> State
instructionIntSubOpp state@(State {_int = i1 : i2 : is}) = state {_int = i1 - i2 : is}
instructionIntSubOpp state = state
-- |Multiplies the top two ints from the int stack and pushes the result to the int stack.
instructionIntMul :: State -> State
instructionIntMul state@(State {_int = i1 : i2 : is}) = state {_int = i2 * i1 : is}
instructionIntMul state = state
-- |Divides the first float from the second float and pushes the result to the int stack.
-- This does truncate.
instructionIntDiv :: State -> State
instructionIntDiv state@(State {_int = i1 : i2 : is}) = state {_int = if i1 /= 0 then (i2 `div` i1) : is else i1 : i2 : is}
instructionIntDiv state = state
-- |Divides the second int from the first int and pushes the result to the int stack.
-- This does truncate.
instructionIntDivOpp :: State -> State
instructionIntDivOpp state@(State {_int = i1 : i2 : is}) = state {_int = if i2 /= 0 then (i1 `div` i2) : is else i1 : i2 : is}
instructionIntDivOpp state = state
-- |Mods the first int from the second int and pushes the result to the int stack.
-- This does truncate.
instructionIntMod :: State -> State
instructionIntMod state@(State {_int = i1 : i2 : is}) = state {_int = if i1 /= 0 then (i2 `mod` i1) : is else i1 : i2 : is}
instructionIntMod state = state
-- |Mods the second int from the first int and pushes the result to the int stack.
-- This does truncate.
instructionIntModOpp :: State -> State
instructionIntModOpp state@(State {_int = i1 : i2 : is}) = state {_int = if i2 /= 0 then (i1 `mod` i2) : is else i1 : i2 : is}
instructionIntModOpp state = state
-- |Takes the top two ints from the int stack and pushes the minimum of the two back on top.
instructionIntMin :: State -> State
instructionIntMin state@(State {_int = i1 : i2 : is}) = state {_int = min i1 i2 : is}
instructionIntMin state = state
-- |Takes the top two ints from the int stack and pushes the maximum of the two back on top.
instructionIntMax :: State -> State
instructionIntMax state@(State {_int = i1 : i2 : is}) = state {_int = max i1 i2 : is}
instructionIntMax state = state
-- |Adds one to the top of the int stack and pushes the result back to the int stack.
instructionIntInc :: State -> State
instructionIntInc state@(State {_int = i1 : is}) = state {_int = i1 + 1 : is}
instructionIntInc state = state
-- |Subtracts one from the top of the int stack and pushes the result back to the int stack.
instructionIntDec :: State -> State
instructionIntDec state@(State {_int = i1 : is}) = state {_int = i1 - 1 : is}
instructionIntDec state = state
-- |Takes the top two ints from the int stack and pushes the result of: the top int item < the second int item
instructionIntLT :: State -> State
instructionIntLT state@(State {_int = i1 : i2 : is, _bool = bs}) = state {_int = is, _bool = (i1 < i2) : bs}
instructionIntLT state = state
-- |Takes the top two ints from the int stack and pushes the result of: the top int item > the second int item
instructionIntGT :: State -> State
instructionIntGT state@(State {_int = i1 : i2 : is, _bool = bs}) = state {_int = is, _bool = (i1 > i2) : bs}
instructionIntGT state = state
-- |Takes the top two ints from the int stack and pushes the result of: the top int item <= the second int item
instructionIntLTE :: State -> State
instructionIntLTE state@(State {_int = i1 : i2 : is, _bool = bs}) = state {_int = is, _bool = (i1 <= i2) : bs}
instructionIntLTE state = state
-- |Takes the top two ints from the int stack and pushes the result of: the top int item >= the second int item
instructionIntGTE :: State -> State
instructionIntGTE state@(State {_int = i1 : i2 : is, _bool = bs}) = state {_int = is, _bool = (i1 >= i2) : bs}
instructionIntGTE state = state
-- |Pops the top int from the int stack.
instructionIntDup :: State -> State
instructionIntDup = instructionDup int
-- |Duplicates the top int on the int stack.
instructionIntPop :: State -> State
instructionIntPop = instructionPop int
-- |Duplicates the second to top int on the int stack based on the top int
-- and pushes the result to the int stack.
instructionIntDupN :: State -> State
instructionIntDupN = instructionDupN int
-- |Swaps the top two ints on the int stack.
instructionIntSwap :: State -> State
instructionIntSwap = instructionSwap int
-- |Rotates the top three ints and pushes the result to the int stack.
instructionIntRot :: State -> State
instructionIntRot = instructionRot int
-- |Sets the int stack to [].
instructionIntFlush :: State -> State
instructionIntFlush = instructionFlush int
-- |Checks if the top two floats are equal
instructionIntEq :: State -> State
instructionIntEq = instructionEq int
-- |Pushes the depth of the int stack to top of the int stack after the caluculation.
instructionIntStackDepth :: State -> State
instructionIntStackDepth = instructionStackDepth int
-- |Moves an item from deep within the int stack to the top of the int stack based on
-- the top int from the int stack.
instructionIntYank :: State -> State
instructionIntYank = instructionYank int
-- |Copies an item from deep within the float stack to the top of the float stack based on
-- the top int from the int stack.
instructionIntYankDup :: State -> State
instructionIntYankDup = instructionYankDup int
-- |Moves an item from the top of the int stack to deep within the int stack based on
-- the top int from the int stack.
instructionIntShove :: State -> State
instructionIntShove = instructionShove int
-- |Copies an item from the top of the int stack to deep within the int stack based on
-- the top int from the int stack.
instructionIntShoveDup :: State -> State
instructionIntShoveDup = instructionShoveDup int
-- |Pushes True to the bool stack if the int stack is empty. False if not.
instructionIntIsStackEmpty :: State -> State
instructionIntIsStackEmpty = instructionIsStackEmpty int
-- |Duplicate the top N items from the int stack based on the top int from the int stack.
instructionIntDupItems :: State -> State
instructionIntDupItems = instructionDupItems int
-- |Pushes the sin of the top int to the int stack. Rounding if needed.
instructionIntSin :: State -> State
instructionIntSin state@(State {_int = i1 : is}) = state {_int = round (sin (fromIntegral @Integer @Double i1)) : is}
instructionIntSin state = state
-- |Pushes the cos of the top int to the int stack. Rounding if needed.
instructionIntCos :: State -> State
instructionIntCos state@(State {_int = i1 : is}) = state {_int = round (cos (fromIntegral @Integer @Double i1)) : is}
instructionIntCos state = state
-- |Pushes the tan of the top int to the int stack. Rounding if needed.
instructionIntTan :: State -> State
instructionIntTan state@(State {_int = i1 : is}) = state {_int = round (tan (fromIntegral @Integer @Double i1)) : is}
instructionIntTan state = state
-- |Pushes the absolute value of the top int to the int stack.
instructionIntAbs :: State -> State
instructionIntAbs state@(State {_int = i1 : is}) = state {_int = abs i1 : is}
instructionIntAbs state = state
-- |Pushes the exponential of the top int to the int stack. Rounding if needed.
instructionIntExp :: State -> State
instructionIntExp state@(State {_int = i1 : is}) = state {_int = round (exp (fromIntegral @Integer @Double i1)) : is}
instructionIntExp state = state
-- |Pushes the log of the top int to the int stack. Rounding if needed.
instructionIntLog :: State -> State
instructionIntLog state@(State {_int = i1 : is}) = state {_int = round (log (fromIntegral @Integer @Double i1)) : is}
instructionIntLog state = state
-- |Pushes the squared value of the top int to the int stack.
instructionIntSquare :: State -> State
instructionIntSquare state@(State {_int = i1 : is}) = state {_int = i1 ^ (2 :: Int) : is}
instructionIntSquare state = state
-- |Pushes the cubed value of the top int to the int stack.
instructionIntCube :: State -> State
instructionIntCube state@(State {_int = i1 : is}) = state {_int = i1 ^ (3 :: Int) : is}
instructionIntCube state = state
-- |Pushes the square rooted value of the top int to the int stack. Rounding if needed.
instructionIntSqrt :: State -> State
instructionIntSqrt state@(State {_int = i1 : is}) = state {_int = round (sqrt (fromIntegral @Integer @Double i1)) : is}
instructionIntSqrt state = state
-- |Pushes the top int with its sign reversed to the top of the int stack.
instructionIntReverseSign :: State -> State
instructionIntReverseSign state@(State {_int = i1 : is}) = state {_int = (-1) * i1 : is}
instructionIntReverseSign state = state
allIntInstructions :: [Gene]
allIntInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,42 @@
module HushGP.Instructions.Opens where
import HushGP.State
import Data.Map qualified as Map
import HushGP.Instructions.GenericInstructions
import HushGP.Instructions.ExecInstructions
import HushGP.Instructions.StringInstructions
import HushGP.Instructions.VectorIntInstructions
import HushGP.Instructions.VectorBoolInstructions
import HushGP.Instructions.VectorFloatInstructions
import HushGP.Instructions.VectorStringInstructions
import HushGP.Instructions.VectorCharInstructions
-- |A Map that takes a Gene and returns how many Blocks it opens.
-- To be used in plushy conversion.
instructionOpens :: Map.Map Gene Int
instructionOpens = Map.fromList [
(StateFunc (instructionExecIf, "instructionExecIf"), 2),
(StateFunc (instructionExecDup, "instructionExecDup"), 1),
(StateFunc (instructionExecDupN, "instructionExecDupN"), 1),
(StateFunc (instructionExecPop, "instructionExecPop"), 1),
(StateFunc (instructionExecSwap, "instructionExecSwap"), 2),
(StateFunc (instructionExecRot, "instructionExecRot"), 3),
(StateFunc (instructionExecShove, "instructionExecShove"), 1),
(StateFunc (instructionExecShoveDup, "instructionExecShoveDup"), 1),
(StateFunc (instructionExecDoRange, "instructionExecDoRange"), 1),
(StateFunc (instructionExecDoCount, "instructionExecDoCount"), 1),
(StateFunc (instructionExecDoTimes, "instructionExecDoTimes"), 1),
(StateFunc (instructionExecWhile, "instructionExecWhile"), 1),
(StateFunc (instructionExecDoWhile, "instructionExecDoWhile"), 1),
(StateFunc (instructionExecWhen, "instructionExecWhen"), 1),
(StateFunc (instructionExecK, "instructionExecK"), 2),
(StateFunc (instructionExecS, "instructionExecS"), 3),
(StateFunc (instructionExecY, "instructionExecY"), 1),
(StateFunc (instructionStringIterate, "instructionStringIterate"), 1),
(StateFunc (instructionVectorIntIterate, "instructionVectorIntIterate"), 1),
(StateFunc (instructionVectorFloatIterate, "instructionVectorFloatIterate"), 1),
(StateFunc (instructionVectorStringIterate, "instructionVectorStringIterate"), 1),
(StateFunc (instructionVectorBoolIterate, "instructionVectorBoolIterate"), 1),
(StateFunc (instructionVectorCharIterate, "instructionVectorCharIterate"), 1),
(StateFunc (instructionNoOpBlock, "instructionNoOpBlock"), 1)
]

View File

@ -0,0 +1,330 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.StringInstructions where
import HushGP.State
import HushGP.Instructions.GenericInstructions
import HushGP.Instructions.Utility
import HushGP.TH
-- |Concats the top two strings on the string stack and pushes the result.
instructionStringConcat :: State -> State
instructionStringConcat = instructionVectorConcat string
-- |Swaps the top two strings on the string stack.
instructionStringSwap :: State -> State
instructionStringSwap = instructionSwap string
-- |Inserts the second string on the string stack into the first string
-- on the string stack based on an int from the int stack.
instructionStringInsertString :: State -> State
instructionStringInsertString = instructionVectorInsertVector string
-- |Takes the first string from the string stack and pushes the first character
-- back to the string stack as a string.
instructionStringFromFirstChar :: State -> State
instructionStringFromFirstChar = instructionVectorFromFirstPrim string
-- |Takes the first string from the string stack and pushes the last character
-- back to the string stack as a string.
instructionStringFromLastChar :: State -> State
instructionStringFromLastChar = instructionVectorFromLastPrim string
-- |Takes the first string from the string stack and pushes the Nth character
-- back to the string stack as a string. N in is the top int of the int stack.
instructionStringFromNthChar :: State -> State
instructionStringFromNthChar = instructionVectorFromNthPrim string
-- |Takes the first two strings from the top of the string stack. Looks for and pushed the
-- index of the second substring inside of the first substring to the int stack.
-- If not found, returns -1.
instructionStringIndexOfString :: State -> State
instructionStringIndexOfString = instructionVectorIndexOfVector string
-- |Takes the first two strings from the top of the string stack. Pushes True to the
-- bool stack if the second string is contained within the first string. Pushes False otherwise.
instructionStringContainsString :: State -> State
instructionStringContainsString = instructionVectorContainsVector string
-- |Takes the first two strings from the top of the string stack. Splits the first string
-- based on the second string and pushes the result to the string stack.
-- pysh reverses this. Check this for propeller
instructionStringSplitOnString :: State -> State
instructionStringSplitOnString = instructionVectorSplitOnVector string
-- |Takes the first three strings from the top of the string stack. Replaces the first instance of
-- the second string within the first string with the third string. Pushes the result to the string stack.
instructionStringReplaceFirstString :: State -> State
instructionStringReplaceFirstString = instructionVectorReplaceVector string (Just 1)
-- |Takes the first three strings from the top of the string stack. Replaces the number of instances based on the of the int stack of
-- the second string within the first string with the third string. Pushes the result to the string stack.
instructionStringReplaceNString :: State -> State
instructionStringReplaceNString = instructionVectorReplaceVectorN string
-- |Takes the first three strings from the top of the string stack. Replaces all instances of
-- the second string within the first string with the third string. Pushes the result to the string stack.
instructionStringReplaceAllString :: State -> State
instructionStringReplaceAllString = instructionVectorReplaceVector string Nothing
-- |Takes the first two strings from the top of the string stack. Removes the first instance of
-- the second string. Pushes the result to the string stack.
instructionStringRemoveFirstString :: State -> State
instructionStringRemoveFirstString = instructionVectorRemoveVector string (Just 1)
-- |Takes the first two strings from the top of the string stack. Removes N instances
-- based on the top int from the int stack of the second string. Pushes the result to the string stack.
instructionStringRemoveNString :: State -> State
instructionStringRemoveNString = instructionVectorRemoveVectorN string
-- |Takes the first two strings from the top of the string stack. Removes all instances of
-- the second string. Pushes the result to the string stack.
instructionStringRemoveAllString :: State -> State
instructionStringRemoveAllString = instructionVectorRemoveVector string Nothing
-- |Counts the amount of occurrences of the second string in the first
-- string. Pushes the result to the string stack.
instructionStringOccurrencesOfString :: State -> State
instructionStringOccurrencesOfString = instructionVectorOccurrencesOfVector string
-- |Inserts the top char of the char stack into the top string of the string
-- stack based on an index from the top int of the int stack.
instructionStringInsertChar :: State -> State
instructionStringInsertChar = instructionVectorInsert char string
-- |Pushes True to the bool stack if the top char on the char stack is within the
-- top string on the string stack. Pushes False otherwise.
instructionStringContainsChar :: State -> State
instructionStringContainsChar = instructionVectorContains char string
-- |Pushes the first index found of the top char of the char stack within the
-- first string in the string stack to the int stack.
instructionStringIndexOfChar :: State -> State
instructionStringIndexOfChar = instructionVectorIndexOf char string
-- |Takes the top string from the string stack and the top
-- char from the char stack. Splits the top string based on
-- the top char and pushes the result to the string stack.
instructionStringSplitOnChar :: State -> State
instructionStringSplitOnChar = instructionVectorSplitOn char string
-- |Takes the top string from the string stack and the two top char from the char stack.
-- Replaces the first instance of the top char with the second char.
instructionStringReplaceFirstChar :: State -> State
instructionStringReplaceFirstChar = instructionVectorReplace char string (Just 1)
-- |Takes the top string from the string stack and the two top char from the char stack.
-- Replaces N instances of the top char with the second char. N is determined by the
-- top int on the int stack.
instructionStringReplaceNChar :: State -> State
instructionStringReplaceNChar = instructionVectorReplaceN char string
-- |Takes the top string from the string stack and the two top char from the char stack.
-- Replaces all instances of the top char with the second char.
instructionStringReplaceAllChar :: State -> State
instructionStringReplaceAllChar = instructionVectorReplace char string Nothing
-- |Takes the top string from the string stack and the top char from the char stack.
-- Removes the first instance of the top char with the second char.
instructionStringRemoveFirstChar :: State -> State
instructionStringRemoveFirstChar = instructionVectorRemove char string (Just 1)
-- |Takes the top string from the string stack and the top char from the char stack.
-- Removes N instances of the top char with the second char. N is pulled from the top
-- of the int stack.
instructionStringRemoveNChar :: State -> State
instructionStringRemoveNChar = instructionVectorRemoveN char string
-- |Takes the top string from the string stack and the top char from the char stack.
-- Removes all instances of the top char with the second char.
instructionStringRemoveAllChar :: State -> State
instructionStringRemoveAllChar = instructionVectorRemove char string Nothing
-- |Takes the top string from the string stack and the top char from the char stack.
-- Counts the amount of occurrences of the top char inside of the top string. Pushes
-- this result to the int stack.
instructionStringOccurrencesOfChar :: State -> State
instructionStringOccurrencesOfChar = instructionVectorOccurrencesOf char string
-- |Takes the top string from the string stack and reverses it. Pushes the reversed string
-- to the top of the stack.
instructionStringReverse :: State -> State
instructionStringReverse = instructionReverse string
-- |Takes the top string from the string stack, takes the first N chars from the top string,
-- and pushes the result to the string stack. N is pulled from the top of the int stack.
instructionStringHead :: State -> State
instructionStringHead = instructionVectorTakeN string
-- |Takes the top string from the string stack, takes the last N chars from the top string,
-- and pushes the result to the string stack. N is pulled from the top of the int stack.
instructionStringTail :: State -> State
instructionStringTail = instructionVectorTakeRN string
-- |Takes the top string from the string stack and the top char from the char stack.
-- Prepends the top char to the top string. Pushes the result to the string stack.
instructionStringPrependChar :: State -> State
instructionStringPrependChar = instructionVectorConj char string
-- |Takes the top string from the string stack and the top char from the char stack.
-- Appends the top char to the top string. Pushes the result to the string stack.
instructionStringAppendChar :: State -> State
instructionStringAppendChar = instructionVectorConjEnd char string
-- |Takes the top string from the string stack and removes the first char
-- from said string. Pushes the result to the string stack.
instructionStringRest :: State -> State
instructionStringRest = instructionVectorRest string
-- |Takes the top string from the string stack and removes the last char
-- from said string. Pushes the result to the string stack.
instructionStringButLast :: State -> State
instructionStringButLast = instructionVectorButLast string
-- |Takes the top string from the string stack and drops the first N characters
-- from said string. Pushes the result to the string stack. N is pulled from the top
-- of the int stack.
instructionStringDrop :: State -> State
instructionStringDrop = instructionVectorDrop string
-- |Takes the top string from the string stack and drops the last N characters
-- from said string. Pushes the result to the string stack. N is pulled from the top
-- of the int stack.
instructionStringButLastN :: State -> State
instructionStringButLastN = instructionVectorDropR string
-- |Takes the top string from the string stack and calculates the length. The length
-- is then pushed to the int stack.
instructionStringLength :: State -> State
instructionStringLength = instructionLength string
-- |Makes an empty string and pushes it to the top of the string stack.
instructionStringMakeEmpty :: State -> State
instructionStringMakeEmpty = instructionVectorMakeEmpty string
-- |Checks to see if the top string is empty on the string stack.
-- Pushes True to the bool stack if empty. Pushes False if not.
instructionStringIsEmptyString :: State -> State
instructionStringIsEmptyString = instructionVectorIsEmpty string
-- |Removes the Nth char from the top string of the string stack. N is pulled
-- from the top of the int stack.
instructionStringRemoveNth :: State -> State
instructionStringRemoveNth = instructionVectorRemoveNth string
-- |Sets the Nth char from the top string of the string stack to the top char from
-- the char stack. N is pulled from the top of the int stack.
instructionStringSetNth :: State -> State
instructionStringSetNth = instructionVectorSetNth char string
-- |Strips the whitespace of the top string on the string stack and pushes the result
-- back to the string stack.
instructionStringStripWhitespace :: State -> State
instructionStringStripWhitespace state@(State {_string = s1 : ss}) = state{_string = strip s1 : ss}
instructionStringStripWhitespace state = state
-- |Converts the top bool from the bool stack to a string. Pushes the result to
-- the string stack.
instructionStringFromBool :: State -> State
instructionStringFromBool = instructionStringFromLens bool
-- |Converts the top int from the int stack to a string. Pushes the result to
-- the string stack.
instructionStringFromInt :: State -> State
instructionStringFromInt = instructionStringFromLens int
-- |Converts the top float from the float stack to a string. Pushes the result to
-- the string stack.
instructionStringFromFloat :: State -> State
instructionStringFromFloat = instructionStringFromLens float
-- |Converts the top char from the char stack to a string. Pushes the result to
-- the string stack.
instructionStringFromChar :: State -> State
instructionStringFromChar = instructionVectorFromPrim char string
-- |Removes the top string from the string stack.
instructionStringPop :: State -> State
instructionStringPop = instructionPop string
-- |Duplicates the top string on the string stack.
instructionStringDup :: State -> State
instructionStringDup = instructionDup string
-- |Duplicates the top string on the string stack N times based off the top of the int stack.
instructionStringDupN :: State -> State
instructionStringDupN = instructionDupN string
-- |Rotates the top three strings on the string stack.
instructionStringRot :: State -> State
instructionStringRot = instructionRot string
-- |Sets the string stack to []
instructionStringFlush :: State -> State
instructionStringFlush = instructionFlush string
-- |Checks to see if the top two strings are equal and pushes the result
-- to the bool stack.
instructionStringEq :: State -> State
instructionStringEq = instructionEq string
-- |Calculates the size of the string stack and pushes the result
-- to the int stack.
instructionStringStackDepth :: State -> State
instructionStringStackDepth = instructionStackDepth string
-- |Moves an item from deep within the string stack to the top of the string stack based on
-- the top int from the int stack.
instructionStringYank :: State -> State
instructionStringYank = instructionYank string
-- |Copies an item from deep within the string stack to the top of the string stack based on
-- the top int from the int stack.
instructionStringYankDup :: State -> State
instructionStringYankDup = instructionYankDup string
-- |Pushes True to the bool stack if the string stack is empty. Pushes False otherwise.
instructionStringIsStackEmpty :: State -> State
instructionStringIsStackEmpty = instructionIsStackEmpty string
-- |Moves an item from the top of the string stack to deep within the string stack based on
-- the top int from the int stack.
instructionStringShove :: State -> State
instructionStringShove = instructionShove string
-- |Copies an item from the top of the string stack to deep within the string stack based on
-- the top int from the int stack.
instructionStringShoveDup :: State -> State
instructionStringShoveDup = instructionShoveDup string
-- |Sorts the top string on the string stack by their ascii value and pushes the result
-- back to the string stack.
instructionStringSort :: State -> State
instructionStringSort = instructionVectorSort string
-- |Sorts the top string on the string stack backwards by their ascii value and pushes the result
-- back to the string stack.
instructionStringSortReverse :: State -> State
instructionStringSortReverse = instructionVectorSortReverse string
-- |Duplicate the top N items from the string stack based on the top int from the int stack.
instructionStringDupItems :: State -> State
instructionStringDupItems = instructionDupItems string
-- |Takes the top string and splits its up into strings of size 1 and pushes all of those
-- strings back onto the string stack.
instructionStringParseToChar :: State -> State
instructionStringParseToChar = instructionVectorParseToPrim string
-- |Uses the top two ints from the top of the int stack to pull a sub string
-- from the top string on the string stack. Pushes the result back to the
-- string stack.
instructionStringSubString :: State -> State
instructionStringSubString = instructionSubVector string
-- |Iterates over the top string on the string stack, applying the top instruction of the
-- exec stack along the way.
instructionStringIterate :: State -> State
instructionStringIterate = instructionVectorIterate char string GeneString instructionStringIterate "instructionStringIterate"
allStringInstructions :: [Gene]
allStringInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,291 @@
module HushGP.Instructions.Utility where
import Data.Char
import Data.List
import Data.Ord
import Control.Lens hiding (index, uncons)
import HushGP.State
-- generic utility
-- |Utility Function: Deletes an item from a list at a specified index.
deleteAt :: Int -> [a] -> [a]
deleteAt idx xs = take idx xs <> drop 1 (drop idx xs)
-- |Utility Function: Combines two tuples containing lists with a value placed between them.
combineTuple :: a -> ([a], [a]) -> [a]
combineTuple val = combineTupleList [val]
-- |Utility Function: Combines two tuples containing lists with a list placed between them.
combineTupleList :: [a] -> ([a], [a]) -> [a]
combineTupleList val tup = fst tup <> val <> snd tup
-- |Utility Function: Inserts a value based on an int at a specified index.
insertAt :: Int -> a -> [a] -> [a]
insertAt idx val xs = combineTuple val (splitAt idx xs)
-- |Utility Function: Replaces a value based on an int at a specified index.
replaceAt :: Int -> a -> [a] -> [a]
replaceAt idx val xs = deleteAt (idx + 1) (insertAt idx val xs)
-- |Utility Function: Takes two ints as indices. Sorts them low to high, sets the start to
-- 0 if the lowest start is less than 0 and the end to the length of the list - 1 if the end
-- if larger than the list. Grabs the sub list of adjusted indices.
subList :: Int -> Int -> [a] -> [a]
subList idx0 idx1 xs =
let
(start, end) = if idx0 <= idx1 then (idx0, idx1) else (idx1, idx0)
adjStart = max 0 start
adjEnd = min end (length xs)
in
take adjEnd (drop adjStart xs)
-- |Utility Function: Finds the index of the second list inside of the first index.
-- If the sublist passed is larger than the full list, returns -1
-- If the lists are of equal length, and then contents are equal, returns 0. If not equal, returns -1
-- Recursively shortens the full list until the sub list is found.
findSubA :: forall a. Eq a => [a] -> [a] -> Int
findSubA fullA subA
| length fullA < length subA = -1
| length fullA == length subA = if fullA == subA then 0 else -1
| otherwise = findSubA' fullA subA 0
where
findSubA' :: [a] -> [a] -> Int -> Int
findSubA' fA sA subIndex
| null fA = -1
| length sA > length fA = -1
| sA == take (length sA) fA = subIndex
| otherwise = findSubA' (drop 1 fA) sA (subIndex + 1)
-- |Utility Function: Replaces a number of instances of old with new in a list.
-- The Maybe Int is the amount of olds to replace with new. Nothing means replace all.
-- Just chain findSubA calls.
-- May not be the most efficient method with the findSubA calls.
replace :: Eq a => [a] -> [a] -> [a] -> Maybe Int -> [a]
replace fullA old new (Just amt) =
if findSubA fullA old /= -1 && amt > 0
then replace (take (findSubA fullA old) fullA <> new <> drop (findSubA fullA old + length old) fullA) old new (Just $ amt - 1)
else fullA
replace fullA old new Nothing =
if findSubA fullA old /= -1
then replace (take (findSubA fullA old) fullA <> new <> drop (findSubA fullA old + length old) fullA) old new Nothing
else fullA
-- |Utility Function: Counts the amount of occurrences of a sub list inside
-- of a larger list.
amtOccurences :: forall a. Eq a => [a] -> [a] -> Int
amtOccurences fullA subA = amtOccurences' fullA subA 0
where
amtOccurences' :: [a] -> [a] -> Int -> Int
amtOccurences' fA sA count =
if findSubA fA sA /= -1
then amtOccurences' (replace fA sA mempty (Just 1)) sA (count + 1)
else count
-- |Utility Function: Takes the last N elements of a list.
takeR :: Int -> [a] -> [a]
takeR amt fullA = drop (length fullA - amt) fullA
-- |Utility Function: Drops the last N elements of a list.
dropR :: Int -> [a] -> [a]
dropR amt fullA = take (length fullA - amt) fullA
-- |Utility Function: A safe version of init. If the list is empty, returns the empty list.
-- If the list has items, takes the init of the list.
safeInit :: [a] -> [a]
safeInit [] = []
safeInit xs = init xs
-- |Utility Function: An indexing strategy used in parts of Hush. Takes the absolute value
-- of the passed number `mod` the length of the passed list.
absNum :: Integral a => a -> [b] -> Int
absNum rawNum lst = abs (fromIntegral rawNum) `mod` length lst
-- |Utility Function: Checks to see if a list is empty.
-- If the list is empty, returns False.
-- If the list is not empty, returns True.
notEmptyStack :: Lens' State [a] -> State -> Bool
notEmptyStack accessor state = not . null $ view accessor state
-- |Utility Function: Extracts an int from a GeneInt.
-- How to make this polymorphic???????? A general function for
-- this would be nice. Wrapped in a maybe too?
extractGeneInt :: Gene -> Integer
extractGeneInt (GeneInt x) = x
extractGeneInt _ = error "todo this later??"
-- bool utility
-- |A template function to make bool comparisons concise.
boolTemplate :: (Bool -> Bool -> Bool) -> State -> State
boolTemplate func state@(State {_bool = b1 : b2 : bs}) = state {_bool = func b1 b2 : bs}
boolTemplate _ state = state
-- |Utility function. Haskell doesn't have its own xor operation.
xor :: Bool -> Bool -> Bool
xor b1 b2
| b1 && not b2 = True
| not b1 && b2 = True
| otherwise = False
-- char utility
-- |Utility: Converts a whole number `mod` 128 to a char.
intToAscii :: Integral a => a -> Char
intToAscii val = chr (abs (fromIntegral val) `mod` 128)
-- code utility
-- |Utility function: Checks to see if a gene is a code block.
-- If it is a block, returns true, else returns false
isBlock :: Gene -> Bool
isBlock (Block _) = True
isBlock _ = False
-- |Utility function: Returns the length of the passed block.
-- If the gene isn't a block, returns 1
blockLength :: Gene -> Integer
blockLength (Block bxs) = toInteger $ length bxs
blockLength _ = 1
-- |Utility function: Returns true if the passed block is empty, false is not.
-- If the passed gene is not a block, returns false
blockIsNull :: Gene -> Bool
blockIsNull (Block bxs) = null bxs
blockIsNull _ = False
-- |Utility Function: A helper function for instructionCodeContainer. The full description is there.
-- https://faculty.hampshire.edu/lspector/push3-description.html#Type
-- CODE.CONTAINER
findContainer :: Gene -> Gene -> Gene
findContainer (Block fullA) gene
| fromIntegral (length fullA) <= blockLength gene = Block []
| gene `elem` fullA = Block [] -- Not allowed to be top level
| any isBlock fullA = findContainer' (filter isBlock fullA) gene
| otherwise = Block []
where
findContainer' :: [Gene] -> Gene -> Gene
findContainer' [] _ = Block []
findContainer' ((Block bx1) : bxs) g = if g `elem` bx1 then Block bx1 else findContainer' bxs g
findContainer' _ _ = Block [] -- This should never happen
findContainer _ _ = Block []
-- |Utility Function: A helper function for instructionCodeDiscrepancy. The full description is there.
countDiscrepancy :: Gene -> Gene -> Integer
-- countDiscrepancy (Block xs) (Block ys) = sum [if uncurry (==) tup then 0 else 1 | tup <- zip xs ys] + abs (toInteger (length xs) - toInteger (length ys))
-- countDiscrepancy (Block xs) (Block ys) = sum [if isBlock (fst tup) && isBlock (snd tup) then uncurry countDiscrepancy tup else if uncurry (==) tup then 0 else 1 | tup <- zip xs ys] + abs (toInteger (length xs) - toInteger (length ys))
countDiscrepancy (Block xs) (Block []) = codeRecursiveSize (Block xs)
countDiscrepancy (Block []) (Block ys) = codeRecursiveSize (Block ys)
countDiscrepancy (Block (x:xs)) (Block (y:ys)) = if x == y then 1 + countDiscrepancy (Block xs) (Block ys) else countDiscrepancy (Block xs) (Block ys)
countDiscrepancy _ (Block ys) = 1 + codeRecursiveSize (Block ys)
countDiscrepancy (Block xs) _ = 1 + codeRecursiveSize (Block xs)
countDiscrepancy xgene ygene = if xgene == ygene then 1 else 0
-- |Utility Function: Extracts the first gene from a block. Returns itself if not a block
extractFirstFromBlock :: Gene -> Gene
extractFirstFromBlock (Block (bx1 : _)) = bx1
extractFirstFromBlock gene = gene
-- |Utility Function: Returns the last gene from a block, [] if the block is empty, and itself if not a block
extractLastFromBlock :: Gene -> Gene
extractLastFromBlock (Block []) = Block []
extractLastFromBlock (Block bxs) = last bxs
extractLastFromBlock gene = gene
-- |Utility Function: Calls init on a block. If the block is empty, returns []. If gene isn't a block, returns itself
extractInitFromBlock :: Gene -> Gene
extractInitFromBlock (Block bxs) = Block (safeInit bxs)
extractInitFromBlock gene = gene
-- |Utility Function: Calls `drop 1` on a block. If gene isn't a block, returns itself
extractTailFromBlock :: Gene -> Gene
extractTailFromBlock (Block bxs) = Block (drop 1 bxs)
extractTailFromBlock _ = Block []
-- |Utility Function: Extracts the code at a point in the genome. Recurses into a nested Block if found. The
-- point is based on an int.
codeAtPoint :: [Gene] -> Int -> Gene
codeAtPoint (gene : _) 0 = gene
codeAtPoint [] _ = Block [] -- Should only happen if an empty block is last Gene in the list of Genes
codeAtPoint ((Block nestedGenes) : genes) index = codeAtPoint (nestedGenes <> genes) (index - 1)
codeAtPoint (_ : genes) index = codeAtPoint genes (index - 1)
-- |Utility Function: Inserts code at a point in the genome. Recurses into a block if found. The point is based
-- on an integer
codeInsertAtPoint :: [Gene] -> Gene -> Int -> [Gene]
codeInsertAtPoint oldGenes gene 0 = gene : oldGenes
codeInsertAtPoint [] gene _ = [gene] -- This shouldn't happen (lol)
codeInsertAtPoint ((Block genes) : oldGenes) gene index = Block (codeInsertAtPoint genes gene (index - 1)) : oldGenes
codeInsertAtPoint (oldGene : oldGenes) gene index = oldGene : codeInsertAtPoint oldGenes gene (index - 1)
-- |Utility Function: Combines two genes together into a block.
codeCombine :: Gene -> Gene -> Gene
codeCombine (Block bxs) (Block bys) = Block (bxs <> bys)
codeCombine (Block bxs) ygene = Block (ygene : bxs)
codeCombine xgene (Block bys) = Block (xgene : bys)
codeCombine xgene ygene = Block [xgene, ygene]
-- |Utility Function: Determines if the second gene is a member of the first gene.
-- If the first gene is a Block and the second gene is also a Block, does a sublist search for the second block in the first block.
-- if the first gene is a Block and the second gene is not, the block is searched for the second gene.
-- If neither of the genes are blocks, returns False.
codeMember :: Gene -> Gene -> Bool
codeMember (Block bxs) (Block bys) = findSubA bxs bys /= (-1)
codeMember (Block bxs) ygene = ygene `elem` bxs
codeMember _ _ = False
-- |Utility Function: Calculates the size of a Block including counting the nested Blocks recursively
codeRecursiveSize :: Gene -> Integer
codeRecursiveSize (Block bxs) = sum [codeRecursiveSize x + if isBlock x then 1 else 0 | x <- bxs]
codeRecursiveSize _ = 1
-- string utility
-- |Utility String: Whitespack characters.
-- shamelessly stolen from https://hackage.haskell.org/package/MissingH-1.6.0.1/docs/src/Data.String.Utils.html#strip
wschars :: String
wschars = " \t\r\n"
-- |Utility Function: Strips a string of its whitespace on both sides.
strip :: String -> String
strip = lstrip . rstrip
-- |Utility Function: Strips a string of its whitespace on the left side.
lstrip :: String -> String
lstrip s = case s of
[] -> []
(x:xs) -> if x `elem` wschars
then lstrip xs
else s
-- |Utility Function: Strips a string of its whitespace on the right side.
-- this is a tad inefficient
rstrip :: String -> String
rstrip = reverse . lstrip . reverse
-- |Utility Function: Casts a type based on a lens to a string. Pushes the result
-- to the string stack.
instructionStringFromLens :: Show a => Lens' State [a] -> State -> State
instructionStringFromLens accessor state@(State {_string = ss}) =
case uncons (view accessor state) of
Nothing -> state
Just (x1,_) -> state{_string = show x1 : ss}
-- vector utilty
-- |Utility Function: Takes a list of numbers and returns the mode of said list.
mode :: (Num a, Ord a) => [a] -> a
mode xs =
case uncons (maximumBy (comparing length) (group (sort xs))) of
Just (x, _) -> x
_ -> error "Error: list is empty when determining mode!"
-- |Utility Function: Calculates the 2-norm of a list and returns it.
twoNorm :: (Floating a) => [a] -> a
twoNorm xs = sqrt $ sum $ map (^ (2 :: Int)) xs
-- |Utility Function: Takes in any value and returns 0. Used primarily to return 0
-- when a function such as maximum is operating on an empty list.
retZero :: (Num b) => a -> b
retZero _ = 0

View File

@ -0,0 +1,335 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.VectorBoolInstructions where
import HushGP.State
import HushGP.Instructions.GenericInstructions
import HushGP.TH
-- |Pops the top bool vector from the bool vector stack.
instructionVectorBoolPop :: State -> State
instructionVectorBoolPop = instructionPop vectorBool
-- |Duplicates the top bool vector from the bool vector stack.
instructionVectorBoolDup :: State -> State
instructionVectorBoolDup = instructionDup vectorBool
-- |Duplicates the top bool vector from the bool vector stack N times
-- based on the top int from the int stack.
instructionVectorBoolDupN :: State -> State
instructionVectorBoolDupN = instructionDupN vectorBool
-- |Swaps the top two bool vectors from the bool vector stack.
instructionVectorBoolSwap :: State -> State
instructionVectorBoolSwap = instructionSwap vectorBool
-- |Rotates the top three bool vectors from the bool vector stack.
instructionVectorBoolRot :: State -> State
instructionVectorBoolRot = instructionRot vectorBool
-- |Sets the vector bool stack to []
instructionVectorBoolFlush :: State -> State
instructionVectorBoolFlush = instructionFlush vectorBool
-- |Pushes True to the bool stack if the top two bool vectors from
-- the vector bool stack are equal. Pushes False otherwise.
instructionVectorBoolEq :: State -> State
instructionVectorBoolEq = instructionEq vectorBool
-- |Calculates the size of the vector bool stack and pushes that number
-- to the int stack.
instructionVectorBoolStackDepth :: State -> State
instructionVectorBoolStackDepth = instructionStackDepth vectorBool
-- |Moves an item from deep within the vector bool stack to the top of the vector bool stack based on
-- the top int from the int stack.
instructionVectorBoolYank :: State -> State
instructionVectorBoolYank = instructionYank vectorBool
-- |Copies an item from deep within the vector bool stack to the top of the vector bool stack based on
-- the top int from the int stack.
instructionVectorBoolYankDup :: State -> State
instructionVectorBoolYankDup = instructionYankDup vectorBool
-- |Pushes True to the bool stack if the vector bool stack is empty. False if not.
instructionVectorBoolIsStackEmpty :: State -> State
instructionVectorBoolIsStackEmpty = instructionIsStackEmpty vectorBool
-- |Moves an item from the top of the vector bool stack to deep within the vector bool stack based on
-- the top int from the int stack.
instructionVectorBoolShove :: State -> State
instructionVectorBoolShove = instructionShove vectorBool
-- |Copies an item from the top of the vector bool stack to deep within the vector bool stack based on
-- the top int from the int stack.
instructionVectorBoolShoveDup :: State -> State
instructionVectorBoolShoveDup = instructionShoveDup vectorBool
-- |Duplicate the top N items from the vector bool stack based on the top int from the int stack.
instructionVectorBoolDupItems :: State -> State
instructionVectorBoolDupItems = instructionDupItems vectorBool
-- |Concats the top two vectors on top of the vector bool stack.
instructionVectorBoolConcat :: State -> State
instructionVectorBoolConcat = instructionVectorConcat vectorBool
-- |Takes the top bool from the bool stack and prepends it to top bool vector
-- on the bool vector stack.
instructionVectorBoolConj :: State -> State
instructionVectorBoolConj = instructionVectorConj bool vectorBool
-- |Takes the top bool from the bool stack and appends it to top bool vector
-- on the bool vector stack.
instructionVectorBoolConjEnd :: State -> State
instructionVectorBoolConjEnd = instructionVectorConjEnd bool vectorBool
-- |Takes the first N bools from the top of the bool vector from the bool vector
-- and pushes the result to the bool vector stack. N is pulled from the top of
-- the int stack.
instructionVectorBoolTakeN :: State -> State
instructionVectorBoolTakeN = instructionVectorTakeN vectorBool
-- |Takes the last N bools from the top of the bool vector from the bool vector
-- and pushes the result to the bool vector stack. N is pulled from the top of
-- the int stack.
instructionVectorBoolTakeRN :: State -> State
instructionVectorBoolTakeRN = instructionVectorTakeRN vectorBool
-- |Takes a sublist of the top bool vector on top of the vector bool stack.
-- The two ints to determine bounds are pulled from the top of the int stack.
instructionVectorBoolSubVector :: State -> State
instructionVectorBoolSubVector = instructionSubVector vectorBool
-- |Takes the first bool from the top of the vector bool stack and places
-- it on the bool stack.
instructionVectorBoolFirst :: State -> State
instructionVectorBoolFirst = instructionVectorFirst bool vectorBool
-- |Takes the first bool from the top of the vector bool stack and places
-- it wrapped in a list on top of the vector bool stack.
instructionVectorBoolFromFirstPrim :: State -> State
instructionVectorBoolFromFirstPrim = instructionVectorFromFirstPrim vectorBool
-- |Takes the first bool from the top of the bool stack and places it
-- wrapped in a list on top of the vector bool stack.
instructionVectorBoolFromPrim :: State -> State
instructionVectorBoolFromPrim = instructionVectorFromPrim bool vectorBool
-- |Takes the last bool from the top of the vector bool stack and places
-- it on the bool stack.
instructionVectorBoolLast :: State -> State
instructionVectorBoolLast = instructionVectorLast bool vectorBool
-- |Takes the last bool from the top bool vector on the vector bool stack and
-- places it on the bool stack.
instructionVectorBoolFromLastPrim :: State -> State
instructionVectorBoolFromLastPrim = instructionVectorFromLastPrim vectorBool
-- |Takes the Nth bool from the top bool vector and places it onto the bool stack
-- based on an int from the top of the int stack.
instructionVectorBoolNth :: State -> State
instructionVectorBoolNth = instructionVectorNth bool vectorBool
-- |Takes the Nth bool from the top bool vector on the vector bool stack and
-- creates a vector wrapping that Nth item, pushing it back onto the vector bool stack.
-- N is the top item on the int stack.
instructionVectorBoolFromNthPrim :: State -> State
instructionVectorBoolFromNthPrim = instructionVectorFromNthPrim vectorBool
-- |Removes the first bool from the top bool vector on the vector bool stack and
-- places the result back onto the vector bool stack.
instructionVectorBoolRest :: State -> State
instructionVectorBoolRest = instructionVectorRest vectorBool
-- |Removes the last bool from the top bool vector on the vector bool stack and
-- places the result back onto the vector bool stack.
instructionVectorBoolButLast :: State -> State
instructionVectorBoolButLast = instructionVectorButLast vectorBool
-- |Drops the first N items from the top bool vector and pushes the result
-- back to the vector bool stack. N is pulled from the top of the int stack.
instructionVectorBoolDrop :: State -> State
instructionVectorBoolDrop = instructionVectorDrop vectorBool
-- |Drops the last N items from the top bool vector and pushes the result
-- back to the vector bool stack. N is pulled from the top of the int stack.
instructionVectorBoolDropR :: State -> State
instructionVectorBoolDropR = instructionVectorDropR vectorBool
-- |Pushes the length of the top bool vector from the vector bool stack
-- to the top of the int stack.
instructionVectorBoolLength :: State -> State
instructionVectorBoolLength = instructionLength vectorBool
-- |Reverses the top bool vector from the vector bool stack and pushes the
-- result to the vector bool stack.
instructionVectorBoolReverse :: State -> State
instructionVectorBoolReverse = instructionReverse vectorBool
-- |Takes the top bool vector from the vector bool stack and pushes the
-- individual bools to the vector bool stack.
instructionVectorBoolPushAll :: State -> State
instructionVectorBoolPushAll = instructionPushAll bool vectorBool
-- |Makes an empty vector and pushes it to the vector bool stack.
instructionVectorBoolMakeEmpty :: State -> State
instructionVectorBoolMakeEmpty = instructionVectorMakeEmpty vectorBool
-- |Checks if the top bool vector from the vector bool stack is empty.
-- Pushes True if the bool vector is empty to the bool stack. False otherwise.
instructionVectorBoolIsEmpty :: State -> State
instructionVectorBoolIsEmpty = instructionVectorIsEmpty vectorBool
-- |If the top bool vector from the vector bool stack contains the top bool from the bool
-- stack, pushes True to the bool stack and pushes False otherwise.
instructionVectorBoolContains :: State -> State
instructionVectorBoolContains = instructionVectorContains bool vectorBool
-- |If the second to top bool vector can be found within the first bool vector from the
-- vector bool stack, pushes True to the bool stack if is found, else False.
instructionVectorBoolContainsVectorBool :: State -> State
instructionVectorBoolContainsVectorBool = instructionVectorContainsVector vectorBool
-- |Finds the first index of the top bool in the bool stack inside of the
-- top bool vector from the vector bool stack and pushes the result to the int stack.
instructionVectorBoolIndexOf :: State -> State
instructionVectorBoolIndexOf = instructionVectorIndexOf bool vectorBool
-- |Searches and pushes the index of the second bool vector inside of the first
-- bool vector to the int stack from the vector bool stack. Pushes -1 if not found.
instructionVectorBoolIndexOfVectorBool :: State -> State
instructionVectorBoolIndexOfVectorBool = instructionVectorIndexOfVector vectorBool
-- |Finds the amount of times the top bool on the bool stack occurs inside of
-- the top bool vector from the vector bool stack and pushes the result to the
-- int stack.
instructionVectorBoolOccurrencesOf :: State -> State
instructionVectorBoolOccurrencesOf = instructionVectorOccurrencesOf bool vectorBool
-- |Counts the amount of occurrences of the second bool vector within the first
-- bool vector. Pushes the result to the int stack.
instructionVectorBoolOccurrencesOfVectorBool :: State -> State
instructionVectorBoolOccurrencesOfVectorBool = instructionVectorOccurrencesOfVector vectorBool
-- |Splits the top bool vector from the vector bool stack into lists of size one and pushes
-- the result back one the vector bool stack.
instructionVectorBoolParseToBool :: State -> State
instructionVectorBoolParseToBool = instructionVectorParseToPrim vectorBool
-- |Sets the Nth index inside of the top bool vector from the vector bool stack to the
-- top value from the primitive stack. N is pulled from the top of the int stack.
instructionVectorBoolSetNth :: State -> State
instructionVectorBoolSetNth = instructionVectorSetNth bool vectorBool
-- |Splits the bool vector on top of the vector bool stack with the bool from the top
-- of the bool stack and pushes the result to the original vector stack.
instructionVectorBoolSplitOn :: State -> State
instructionVectorBoolSplitOn = instructionVectorSplitOn bool vectorBool
-- |Splits the first bool vector based on the second bool vector from the vector
-- bool stack and pushes the result to the vector bool stack.
instructionVectorBoolSplitOnVectorBool :: State -> State
instructionVectorBoolSplitOnVectorBool = instructionVectorSplitOnVector vectorBool
-- |Replaces the first occurrence of the top bool with the second bool from
-- the bool stack inside of the top bool vector from the vector bool stack.
-- Pushes the modified bool vector to the vector bool stack.
instructionVectorBoolReplaceFirst :: State -> State
instructionVectorBoolReplaceFirst = instructionVectorReplace bool vectorBool (Just 1)
-- |Replaces all occurrences of the top bool with the second bool from
-- the bool stack inside of the top bool vector from the vector bool stack.
-- Pushes the modified bool vector to the vector bool stack.
instructionVectorBoolReplaceAll :: State -> State
instructionVectorBoolReplaceAll = instructionVectorReplace bool vectorBool Nothing
-- |Replaces N occurrences of the top bool with the second bool from
-- the bool stack inside of the top bool vector from the vector bool stack.
-- Pushes the modified bool vector to the vector bool stack. N is pulled from
-- the top of the int stack.
instructionVectorBoolReplaceN :: State -> State
instructionVectorBoolReplaceN = instructionVectorReplaceN bool vectorBool
-- |Replaces the first occurrence of the second bool vector with the third bool vector
-- inside of the first bool vector from the vector bool stack. Pushes the result to the
-- vector bool stack.
instructionVectorBoolReplaceFirstVectorBool :: State -> State
instructionVectorBoolReplaceFirstVectorBool = instructionVectorReplaceVector vectorBool (Just 1)
-- |Replaces all occurrences of the second bool vector with the third bool vector
-- inside of the first bool vector from the vector bool stack. Pushes the result to the
-- vector bool stack.
instructionVectorBoolReplaceAllVectorBool :: State -> State
instructionVectorBoolReplaceAllVectorBool = instructionVectorReplaceVector vectorBool Nothing
-- |Replaces N occurrences of the second bool vector with the third bool vector
-- inside of the first bool vector from the vector bool stack. Pushes the result to the
-- vector bool stack. N is pulled from the top of the int stack.
instructionVectorBoolReplaceVectorBoolN :: State -> State
instructionVectorBoolReplaceVectorBoolN = instructionVectorReplaceVectorN vectorBool
-- |Removes the first occurrence of the top bool from
-- the bool stack inside of the top bool vector from the vector bool stack.
-- Pushes the modified bool vector to the vector bool stack.
instructionVectorBoolRemoveFirst :: State -> State
instructionVectorBoolRemoveFirst = instructionVectorRemove bool vectorBool (Just 1)
-- |Removes the all occurrences of the top bool from
-- the bool stack inside of the top bool vector from the vector bool stack.
-- Pushes the modified bool vector to the vector bool stack.
instructionVectorBoolRemoveAll :: State -> State
instructionVectorBoolRemoveAll = instructionVectorRemove bool vectorBool Nothing
-- |Removes N occurrences of the top bool from
-- the bool stack inside of the top bool vector from the vector bool stack.
-- Pushes the modified bool vector to the vector bool stack. N is pulled
-- from the top of the int stack.
instructionVectorBoolRemoveN :: State -> State
instructionVectorBoolRemoveN = instructionVectorRemoveN bool vectorBool
-- |Removes the first occurrence of the second bool vector
-- inside of the first bool vector from the vector bool stack. Pushes the result to the
-- vector bool stack.
instructionVectorBoolRemoveFirstVectorBool :: State -> State
instructionVectorBoolRemoveFirstVectorBool = instructionVectorRemoveVector vectorBool (Just 1)
-- |Removes all occurrences of the second bool vector
-- inside of the first bool vector from the vector bool stack. Pushes the result to the
-- vector bool stack.
instructionVectorBoolRemoveAllVectorBool :: State -> State
instructionVectorBoolRemoveAllVectorBool = instructionVectorRemoveVector vectorBool Nothing
-- |Removes N occurrences of the second bool vector
-- inside of the first bool vector from the vector bool stack. Pushes the result to the
-- vector bool stack. N is pulled from the top of the int stack.
instructionVectorBoolRemoveNVectorBool :: State -> State
instructionVectorBoolRemoveNVectorBool = instructionVectorRemoveVectorN vectorBool
-- |Iterates over the top bool vector on the vector bool stack, applying the top instruction of the
-- exec stack along the way.
instructionVectorBoolIterate :: State -> State
instructionVectorBoolIterate = instructionVectorIterate bool vectorBool GeneVectorBool instructionVectorBoolIterate "instructionVectorBoolIterate"
-- |Sorts the top bool vector on the vector bool stack and pushes the result back to the
-- vector bool stack.
instructionVectorBoolSort :: State -> State
instructionVectorBoolSort = instructionVectorSort vectorBool
-- |Sorts the top bool vector on the vector bool stack, reverses it, and pushes the result back to the
-- vector bool stack.
instructionVectorBoolSortReverse :: State -> State
instructionVectorBoolSortReverse = instructionVectorSortReverse vectorBool
-- |Inserts the top bool from the bool stack into the top bool vector from the
-- vector bool stack at a specified index and pushes the result to the vector
-- bool stack. The index is pulled from the top of the int stack.
instructionVectorBoolInsert :: State -> State
instructionVectorBoolInsert = instructionVectorInsert bool vectorBool
-- |Inserts the second bool vector into the first bool vector from the vector bool stack
-- at a specified index and pushes the result to the vector bool stack. The index is
-- pulled from the top of the int stack.
instructionVectorBoolInsertVectorBool :: State -> State
instructionVectorBoolInsertVectorBool = instructionVectorInsertVector vectorBool
allVectorBoolInstructions :: [Gene]
allVectorBoolInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,335 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.VectorCharInstructions where
import HushGP.State
import HushGP.Instructions.GenericInstructions
import HushGP.TH
-- |Pops the top char vector from the char vector stack.
instructionVectorCharPop :: State -> State
instructionVectorCharPop = instructionPop vectorChar
-- |Duplicates the top char vector from the char vector stack.
instructionVectorCharDup :: State -> State
instructionVectorCharDup = instructionDup vectorChar
-- |Duplicates the top char vector from the char vector stack N times
-- based on the top int from the int stack.
instructionVectorCharDupN :: State -> State
instructionVectorCharDupN = instructionDupN vectorChar
-- |Swaps the top two char vectors from the char vector stack.
instructionVectorCharSwap :: State -> State
instructionVectorCharSwap = instructionSwap vectorChar
-- |Rotates the top three char vectors from the char vector stack.
instructionVectorCharRot :: State -> State
instructionVectorCharRot = instructionRot vectorChar
-- |Sets the vector char stack to []
instructionVectorCharFlush :: State -> State
instructionVectorCharFlush = instructionFlush vectorChar
-- |Pushes True to the bool stack if the top two char vectors from
-- the vector char stack are equal. Pushes False otherwise.
instructionVectorCharEq :: State -> State
instructionVectorCharEq = instructionEq vectorChar
-- |Calculates the size of the vector char stack and pushes that number
-- to the int stack.
instructionVectorCharStackDepth :: State -> State
instructionVectorCharStackDepth = instructionStackDepth vectorChar
-- |Moves an item from deep within the vector char stack to the top of the vector char stack based on
-- the top int from the int stack.
instructionVectorCharYank :: State -> State
instructionVectorCharYank = instructionYank vectorChar
-- |Copies an item from deep within the vector char stack to the top of the vector char stack based on
-- the top int from the int stack.
instructionVectorCharYankDup :: State -> State
instructionVectorCharYankDup = instructionYankDup vectorChar
-- |Pushes True to the bool stack if the vector char stack is empty. False if not.
instructionVectorCharIsStackEmpty :: State -> State
instructionVectorCharIsStackEmpty = instructionIsStackEmpty vectorChar
-- |Moves an item from the top of the vector char stack to deep within the vector char stack based on
-- the top int from the int stack.
instructionVectorCharShove :: State -> State
instructionVectorCharShove = instructionShove vectorChar
-- |Copies an item from the top of the vector char stack to deep within the vector char stack based on
-- the top int from the int stack.
instructionVectorCharShoveDup :: State -> State
instructionVectorCharShoveDup = instructionShoveDup vectorChar
-- |Duplicate the top N items from the vector char stack based on the top int from the int stack.
instructionVectorCharDupItems :: State -> State
instructionVectorCharDupItems = instructionDupItems vectorChar
-- |Concats the top two vectors on top of the vector char stack.
instructionVectorCharConcat :: State -> State
instructionVectorCharConcat = instructionVectorConcat vectorChar
-- |Takes the top char from the char stack and prepends it to top char vector
-- on the char vector stack.
instructionVectorCharConj :: State -> State
instructionVectorCharConj = instructionVectorConj char vectorChar
-- |Takes the top char from the char stack and appends it to top char vector
-- on the char vector stack.
instructionVectorCharConjEnd :: State -> State
instructionVectorCharConjEnd = instructionVectorConjEnd char vectorChar
-- |Takes the first N chars from the top of the char vector from the char vector
-- and pushes the result to the char vector stack. N is pulled from the top of
-- the int stack.
instructionVectorCharTakeN :: State -> State
instructionVectorCharTakeN = instructionVectorTakeN vectorChar
-- |Takes the last N chars from the top of the char vector from the char vector
-- and pushes the result to the char vector stack. N is pulled from the top of
-- the int stack.
instructionVectorCharTakeRN :: State -> State
instructionVectorCharTakeRN = instructionVectorTakeRN vectorChar
-- |Takes a sublist of the top char vector on top of the vector char stack.
-- The two ints to determine bounds are pulled from the top of the int stack.
instructionVectorCharSubVector :: State -> State
instructionVectorCharSubVector = instructionSubVector vectorChar
-- |Takes the first char from the top of the vector char stack and places
-- it on the char stack.
instructionVectorCharFirst :: State -> State
instructionVectorCharFirst = instructionVectorFirst char vectorChar
-- |Takes the first char from the top of the vector char stack and places
-- it wrapped in a list on top of the vector char stack.
instructionVectorCharFromFirstPrim :: State -> State
instructionVectorCharFromFirstPrim = instructionVectorFromFirstPrim vectorChar
-- |Takes the first char from the top of the char stack and places it
-- wrapped in a list on top of the vector char stack.
instructionVectorCharFromPrim :: State -> State
instructionVectorCharFromPrim = instructionVectorFromPrim char vectorChar
-- |Takes the last char from the top of the vector char stack and places
-- it on the char stack.
instructionVectorCharLast :: State -> State
instructionVectorCharLast = instructionVectorLast char vectorChar
-- |Takes the last char from the top char vector on the vector char stack and
-- places it on the char stack.
instructionVectorCharFromLastPrim :: State -> State
instructionVectorCharFromLastPrim = instructionVectorFromLastPrim vectorChar
-- |Takes the Nth char from the top char vector and places it onto the char stack
-- based on an int from the top of the int stack.
instructionVectorCharNth :: State -> State
instructionVectorCharNth = instructionVectorNth char vectorChar
-- |Takes the Nth char from the top char vector on the vector char stack and
-- creates a vector wrapping that Nth item, pushing it back onto the vector char stack.
-- N is the top item on the int stack.
instructionVectorCharFromNthPrim :: State -> State
instructionVectorCharFromNthPrim = instructionVectorFromNthPrim vectorChar
-- |Removes the first char from the top char vector on the vector char stack and
-- places the result back onto the vector char stack.
instructionVectorCharRest :: State -> State
instructionVectorCharRest = instructionVectorRest vectorChar
-- |Removes the last char from the top char vector on the vector char stack and
-- places the result back onto the vector char stack.
instructionVectorCharButLast :: State -> State
instructionVectorCharButLast = instructionVectorButLast vectorChar
-- |Drops the first N items from the top char vector and pushes the result
-- back to the vector char stack. N is pulled from the top of the int stack.
instructionVectorCharDrop :: State -> State
instructionVectorCharDrop = instructionVectorDrop vectorChar
-- |Drops the last N items from the top char vector and pushes the result
-- back to the vector char stack. N is pulled from the top of the int stack.
instructionVectorCharDropR :: State -> State
instructionVectorCharDropR = instructionVectorDropR vectorChar
-- |Pushes the length of the top char vector from the vector char stack
-- to the top of the int stack.
instructionVectorCharLength :: State -> State
instructionVectorCharLength = instructionLength vectorChar
-- |Reverses the top char vector from the vector char stack and pushes the
-- result to the vector char stack.
instructionVectorCharReverse :: State -> State
instructionVectorCharReverse = instructionReverse vectorChar
-- |Takes the top char vector from the vector char stack and pushes the
-- individual chars to the vector char stack.
instructionVectorCharPushAll :: State -> State
instructionVectorCharPushAll = instructionPushAll char vectorChar
-- |Makes an empty vector and pushes it to the vector char stack.
instructionVectorCharMakeEmpty :: State -> State
instructionVectorCharMakeEmpty = instructionVectorMakeEmpty vectorChar
-- |Checks if the top char vector from the vector char stack is empty.
-- Pushes True if the char vector is empty to the bool stack. False otherwise.
instructionVectorCharIsEmpty :: State -> State
instructionVectorCharIsEmpty = instructionVectorIsEmpty vectorChar
-- |If the top char vector from the vector char stack contains the top char from the char
-- stack, pushes True to the bool stack and pushes False otherwise.
instructionVectorCharContains :: State -> State
instructionVectorCharContains = instructionVectorContains char vectorChar
-- |If the second to top char vector can be found within the first char vector from the
-- vector char stack, pushes True to the bool stack if is found, else False.
instructionVectorCharContainsVectorChar :: State -> State
instructionVectorCharContainsVectorChar = instructionVectorContainsVector vectorChar
-- |Finds the first index of the top char in the char stack inside of the
-- top char vector from the vector char stack and pushes the result to the int stack.
instructionVectorCharIndexOf :: State -> State
instructionVectorCharIndexOf = instructionVectorIndexOf char vectorChar
-- |Searches and pushes the index of the second char vector inside of the first
-- char vector to the int stack from the vector char stack. Pushes -1 if not found.
instructionVectorCharIndexOfVectorChar :: State -> State
instructionVectorCharIndexOfVectorChar = instructionVectorIndexOfVector vectorChar
-- |Finds the amount of times the top char on the char stack occurs inside of
-- the top char vector from the vector char stack and pushes the result to the
-- int stack.
instructionVectorCharOccurrencesOf :: State -> State
instructionVectorCharOccurrencesOf = instructionVectorOccurrencesOf char vectorChar
-- |Counts the amount of occurrences of the second char vector within the first
-- char vector. Pushes the result to the int stack.
instructionVectorCharOccurrencesOfVectorChar :: State -> State
instructionVectorCharOccurrencesOfVectorChar = instructionVectorOccurrencesOfVector vectorChar
-- |Splits the top char vector from the vector char stack into lists of size one and pushes
-- the result back one the vector char stack.
instructionVectorCharParseToChar :: State -> State
instructionVectorCharParseToChar = instructionVectorParseToPrim vectorChar
-- |Sets the Nth index inside of the top char vector from the vector char stack to the
-- top value from the primitive stack. N is pulled from the top of the int stack.
instructionVectorCharSetNth :: State -> State
instructionVectorCharSetNth = instructionVectorSetNth char vectorChar
-- |Splits the char vector on top of the vector char stack with the char from the top
-- of the char stack and pushes the result to the original vector stack.
instructionVectorCharSplitOn :: State -> State
instructionVectorCharSplitOn = instructionVectorSplitOn char vectorChar
-- |Splits the first char vector based on the second char vector from the vector
-- char stack and pushes the result to the vector char stack.
instructionVectorCharSplitOnVectorChar :: State -> State
instructionVectorCharSplitOnVectorChar = instructionVectorSplitOnVector vectorChar
-- |Replaces the first occurrence of the top char with the second char from
-- the char stack inside of the top char vector from the vector char stack.
-- Pushes the modified char vector to the vector char stack.
instructionVectorCharReplaceFirst :: State -> State
instructionVectorCharReplaceFirst = instructionVectorReplace char vectorChar (Just 1)
-- |Replaces all occurrences of the top char with the second char from
-- the char stack inside of the top char vector from the vector char stack.
-- Pushes the modified char vector to the vector char stack.
instructionVectorCharReplaceAll :: State -> State
instructionVectorCharReplaceAll = instructionVectorReplace char vectorChar Nothing
-- |Replaces N occurrences of the top char with the second char from
-- the char stack inside of the top char vector from the vector char stack.
-- Pushes the modified char vector to the vector char stack. N is pulled from
-- the top of the int stack.
instructionVectorCharReplaceN :: State -> State
instructionVectorCharReplaceN = instructionVectorReplaceN char vectorChar
-- |Replaces the first occurrence of the second char vector with the third char vector
-- inside of the first char vector from the vector char stack. Pushes the result to the
-- vector char stack.
instructionVectorCharReplaceFirstVectorChar :: State -> State
instructionVectorCharReplaceFirstVectorChar = instructionVectorReplaceVector vectorChar (Just 1)
-- |Replaces all occurrences of the second char vector with the third char vector
-- inside of the first char vector from the vector char stack. Pushes the result to the
-- vector char stack.
instructionVectorCharReplaceAllVectorChar :: State -> State
instructionVectorCharReplaceAllVectorChar = instructionVectorReplaceVector vectorChar Nothing
-- |Replaces N occurrences of the second char vector with the third char vector
-- inside of the first char vector from the vector char stack. Pushes the result to the
-- vector char stack. N is pulled from the top of the int stack.
instructionVectorCharReplaceVectorCharN :: State -> State
instructionVectorCharReplaceVectorCharN = instructionVectorReplaceVectorN vectorChar
-- |Removes the first occurrence of the top char from
-- the char stack inside of the top char vector from the vector char stack.
-- Pushes the modified char vector to the vector char stack.
instructionVectorCharRemoveFirst :: State -> State
instructionVectorCharRemoveFirst = instructionVectorRemove char vectorChar (Just 1)
-- |Removes the all occurrences of the top char from
-- the char stack inside of the top char vector from the vector char stack.
-- Pushes the modified char vector to the vector char stack.
instructionVectorCharRemoveAll :: State -> State
instructionVectorCharRemoveAll = instructionVectorRemove char vectorChar Nothing
-- |Removes N occurrences of the top char from
-- the char stack inside of the top char vector from the vector char stack.
-- Pushes the modified char vector to the vector char stack. N is pulled
-- from the top of the int stack.
instructionVectorCharRemoveN :: State -> State
instructionVectorCharRemoveN = instructionVectorRemoveN char vectorChar
-- |Removes the first occurrence of the second char vector
-- inside of the first char vector from the vector char stack. Pushes the result to the
-- vector char stack.
instructionVectorCharRemoveFirstVectorChar :: State -> State
instructionVectorCharRemoveFirstVectorChar = instructionVectorRemoveVector vectorChar (Just 1)
-- |Removes all occurrences of the second char vector
-- inside of the first char vector from the vector char stack. Pushes the result to the
-- vector char stack.
instructionVectorCharRemoveAllVectorChar :: State -> State
instructionVectorCharRemoveAllVectorChar = instructionVectorRemoveVector vectorChar Nothing
-- |Removes N occurrences of the second char vector
-- inside of the first char vector from the vector char stack. Pushes the result to the
-- vector char stack. N is pulled from the top of the int stack.
instructionVectorCharRemoveNVectorChar :: State -> State
instructionVectorCharRemoveNVectorChar = instructionVectorRemoveVectorN vectorChar
-- |Iterates over the top char vector on the vector char stack, applying the top instruction of the
-- exec stack along the way.
instructionVectorCharIterate :: State -> State
instructionVectorCharIterate = instructionVectorIterate char vectorChar GeneVectorChar instructionVectorCharIterate "instructionVectorCharIterate"
-- |Sorts the top char vector on the vector char stack and pushes the result back to the
-- vector char stack.
instructionVectorCharSort :: State -> State
instructionVectorCharSort = instructionVectorSort vectorChar
-- |Sorts the top char vector on the vector char stack, reverses it, and pushes the result back to the
-- vector char stack.
instructionVectorCharSortReverse :: State -> State
instructionVectorCharSortReverse = instructionVectorSortReverse vectorChar
-- |Inserts the top char from the char stack into the top char vector from the
-- vector char stack at a specified index and pushes the result to the vector
-- char stack. The index is pulled from the top of the int stack.
instructionVectorCharInsert :: State -> State
instructionVectorCharInsert = instructionVectorInsert char vectorChar
-- |Inserts the second char vector into the first char vector from the vector char stack
-- at a specified index and pushes the result to the vector char stack. The index is
-- pulled from the top of the int stack.
instructionVectorCharInsertVectorChar :: State -> State
instructionVectorCharInsertVectorChar = instructionVectorInsertVector vectorChar
allVectorCharInstructions :: [Gene]
allVectorCharInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,427 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.VectorFloatInstructions where
import HushGP.State
import HushGP.Instructions.GenericInstructions
import HushGP.TH
import HushGP.Instructions.Utility
-- |Pops the top float vector from the float vector stack.
instructionVectorFloatPop :: State -> State
instructionVectorFloatPop = instructionPop vectorFloat
-- |Duplicates the top float vector from the float vector stack.
instructionVectorFloatDup :: State -> State
instructionVectorFloatDup = instructionDup vectorFloat
-- |Duplicates the top float vector from the float vector stack N times
-- based on the top int from the int stack.
instructionVectorFloatDupN :: State -> State
instructionVectorFloatDupN = instructionDupN vectorFloat
-- |Swaps the top two float vectors from the float vector stack.
instructionVectorFloatSwap :: State -> State
instructionVectorFloatSwap = instructionSwap vectorFloat
-- |Rotates the top three float vectors from the float vector stack.
instructionVectorFloatRot :: State -> State
instructionVectorFloatRot = instructionRot vectorFloat
-- |Sets the vector float stack to []
instructionVectorFloatFlush :: State -> State
instructionVectorFloatFlush = instructionFlush vectorFloat
-- |Pushes True to the bool stack if the top two float vectors from
-- the vector float stack are equal. Pushes False otherwise.
instructionVectorFloatEq :: State -> State
instructionVectorFloatEq = instructionEq vectorFloat
-- |Calculates the size of the vector float stack and pushes that number
-- to the int stack.
instructionVectorFloatStackDepth :: State -> State
instructionVectorFloatStackDepth = instructionStackDepth vectorFloat
-- |Moves an item from deep within the vector float stack to the top of the vector float stack based on
-- the top int from the int stack.
instructionVectorFloatYank :: State -> State
instructionVectorFloatYank = instructionYank vectorFloat
-- |Copies an item from deep within the vector float stack to the top of the vector float stack based on
-- the top int from the int stack.
instructionVectorFloatYankDup :: State -> State
instructionVectorFloatYankDup = instructionYankDup vectorFloat
-- |Pushes True to the bool stack if the vector float stack is empty. False if not.
instructionVectorFloatIsStackEmpty :: State -> State
instructionVectorFloatIsStackEmpty = instructionIsStackEmpty vectorFloat
-- |Moves an item from the top of the vector float stack to deep within the vector float stack based on
-- the top int from the int stack.
instructionVectorFloatShove :: State -> State
instructionVectorFloatShove = instructionShove vectorFloat
-- |Copies an item from the top of the vector float stack to deep within the vector float stack based on
-- the top int from the int stack.
instructionVectorFloatShoveDup :: State -> State
instructionVectorFloatShoveDup = instructionShoveDup vectorFloat
-- |Duplicate the top N items from the vector float stack based on the top int from the int stack.
instructionVectorFloatDupItems :: State -> State
instructionVectorFloatDupItems = instructionDupItems vectorFloat
-- |Concats the top two vectors on top of the vector float stack.
instructionVectorFloatConcat :: State -> State
instructionVectorFloatConcat = instructionVectorConcat vectorFloat
-- |Takes the top float from the float stack and prepends it to top float vector
-- on the float vector stack.
instructionVectorFloatConj :: State -> State
instructionVectorFloatConj = instructionVectorConj float vectorFloat
-- |Takes the top float from the float stack and appends it to top float vector
-- on the float vector stack.
instructionVectorFloatConjEnd :: State -> State
instructionVectorFloatConjEnd = instructionVectorConjEnd float vectorFloat
-- |Takes the first N floats from the top of the float vector from the float vector
-- and pushes the result to the float vector stack. N is pulled from the top of
-- the int stack.
instructionVectorFloatTakeN :: State -> State
instructionVectorFloatTakeN = instructionVectorTakeN vectorFloat
-- |Takes the last N floats from the top of the float vector from the float vector
-- and pushes the result to the float vector stack. N is pulled from the top of
-- the int stack.
instructionVectorFloatTakeRN :: State -> State
instructionVectorFloatTakeRN = instructionVectorTakeRN vectorFloat
-- |Takes a sublist of the top float vector on top of the vector float stack.
-- The two ints to determine bounds are pulled from the top of the int stack.
instructionVectorFloatSubVector :: State -> State
instructionVectorFloatSubVector = instructionSubVector vectorFloat
-- |Takes the first float from the top of the vector float stack and places
-- it on the float stack.
instructionVectorFloatFirst :: State -> State
instructionVectorFloatFirst = instructionVectorFirst float vectorFloat
-- |Takes the first float from the top of the vector float stack and places
-- it wrapped in a list on top of the vector float stack.
instructionVectorFloatFromFirstPrim :: State -> State
instructionVectorFloatFromFirstPrim = instructionVectorFromFirstPrim vectorFloat
-- |Takes the first float from the top of the float stack and places it
-- wrapped in a list on top of the vector float stack.
instructionVectorFloatFromPrim :: State -> State
instructionVectorFloatFromPrim = instructionVectorFromPrim float vectorFloat
-- |Takes the last float from the top of the vector float stack and places
-- it on the float stack.
instructionVectorFloatLast :: State -> State
instructionVectorFloatLast = instructionVectorLast float vectorFloat
-- |Takes the last float from the top float vector on the vector float stack and
-- places it on the float stack.
instructionVectorFloatFromLastPrim :: State -> State
instructionVectorFloatFromLastPrim = instructionVectorFromLastPrim vectorFloat
-- |Takes the Nth float from the top float vector and places it onto the float stack
-- based on an int from the top of the int stack.
instructionVectorFloatNth :: State -> State
instructionVectorFloatNth = instructionVectorNth float vectorFloat
-- |Takes the Nth float from the top float vector on the vector float stack and
-- creates a vector wrapping that Nth item, pushing it back onto the vector float stack.
-- N is the top item on the int stack.
instructionVectorFloatFromNthPrim :: State -> State
instructionVectorFloatFromNthPrim = instructionVectorFromNthPrim vectorFloat
-- |Removes the first float from the top float vector on the vector float stack and
-- places the result back onto the vector float stack.
instructionVectorFloatRest :: State -> State
instructionVectorFloatRest = instructionVectorRest vectorFloat
-- |Removes the last float from the top float vector on the vector float stack and
-- places the result back onto the vector float stack.
instructionVectorFloatButLast :: State -> State
instructionVectorFloatButLast = instructionVectorButLast vectorFloat
-- |Drops the first N items from the top float vector and pushes the result
-- back to the vector float stack. N is pulled from the top of the int stack.
instructionVectorFloatDrop :: State -> State
instructionVectorFloatDrop = instructionVectorDrop vectorFloat
-- |Drops the last N items from the top float vector and pushes the result
-- back to the vector float stack. N is pulled from the top of the int stack.
instructionVectorFloatDropR :: State -> State
instructionVectorFloatDropR = instructionVectorDropR vectorFloat
-- |Pushes the length of the top float vector from the vector float stack
-- to the top of the int stack.
instructionVectorFloatLength :: State -> State
instructionVectorFloatLength = instructionLength vectorFloat
-- |Reverses the top float vector from the vector float stack and pushes the
-- result to the vector float stack.
instructionVectorFloatReverse :: State -> State
instructionVectorFloatReverse = instructionReverse vectorFloat
-- |Takes the top float vector from the vector float stack and pushes the
-- individual floats to the vector float stack.
instructionVectorFloatPushAll :: State -> State
instructionVectorFloatPushAll = instructionPushAll float vectorFloat
-- |Makes an empty vector and pushes it to the vector float stack.
instructionVectorFloatMakeEmpty :: State -> State
instructionVectorFloatMakeEmpty = instructionVectorMakeEmpty vectorFloat
-- |Checks if the top float vector from the vector float stack is empty.
-- Pushes True if the float vector is empty to the bool stack. False otherwise.
instructionVectorFloatIsEmpty :: State -> State
instructionVectorFloatIsEmpty = instructionVectorIsEmpty vectorFloat
-- |If the top float vector from the vector float stack contains the top float from the float
-- stack, pushes True to the bool stack and pushes False otherwise.
instructionVectorFloatContains :: State -> State
instructionVectorFloatContains = instructionVectorContains float vectorFloat
-- |If the second to top float vector can be found within the first float vector from the
-- vector float stack, pushes True to the bool stack if is found, else False.
instructionVectorFloatContainsVectorFloat :: State -> State
instructionVectorFloatContainsVectorFloat = instructionVectorContainsVector vectorFloat
-- |Finds the first index of the top float in the float stack inside of the
-- top float vector from the vector float stack and pushes the result to the int stack.
instructionVectorFloatIndexOf :: State -> State
instructionVectorFloatIndexOf = instructionVectorIndexOf float vectorFloat
-- |Searches and pushes the index of the second float vector inside of the first
-- float vector to the int stack from the vector float stack. Pushes -1 if not found.
instructionVectorFloatIndexOfVectorFloat :: State -> State
instructionVectorFloatIndexOfVectorFloat = instructionVectorIndexOfVector vectorFloat
-- |Finds the amount of times the top float on the float stack occurs inside of
-- the top float vector from the vector float stack and pushes the result to the
-- int stack.
instructionVectorFloatOccurrencesOf :: State -> State
instructionVectorFloatOccurrencesOf = instructionVectorOccurrencesOf float vectorFloat
-- |Counts the amount of occurrences of the second float vector within the first
-- float vector. Pushes the result to the int stack.
instructionVectorFloatOccurrencesOfVectorFloat :: State -> State
instructionVectorFloatOccurrencesOfVectorFloat = instructionVectorOccurrencesOfVector vectorFloat
-- |Splits the top float vector from the vector float stack into lists of size one and pushes
-- the result back one the vector float stack.
instructionVectorFloatParseToFloat :: State -> State
instructionVectorFloatParseToFloat = instructionVectorParseToPrim vectorFloat
-- |Sets the Nth index inside of the top float vector from the vector float stack to the
-- top value from the primitive stack. N is pulled from the top of the int stack.
instructionVectorFloatSetNth :: State -> State
instructionVectorFloatSetNth = instructionVectorSetNth float vectorFloat
-- |Splits the float vector on top of the vector float stack with the float from the top
-- of the float stack and pushes the result to the original vector stack.
instructionVectorFloatSplitOn :: State -> State
instructionVectorFloatSplitOn = instructionVectorSplitOn float vectorFloat
-- |Splits the first float vector based on the second float vector from the vector
-- float stack and pushes the result to the vector float stack.
instructionVectorFloatSplitOnVectorFloat :: State -> State
instructionVectorFloatSplitOnVectorFloat = instructionVectorSplitOnVector vectorFloat
-- |Replaces the first occurrence of the top float with the second float from
-- the float stack inside of the top float vector from the vector float stack.
-- Pushes the modified float vector to the vector float stack.
instructionVectorFloatReplaceFirst :: State -> State
instructionVectorFloatReplaceFirst = instructionVectorReplace float vectorFloat (Just 1)
-- |Replaces all occurrences of the top float with the second float from
-- the float stack inside of the top float vector from the vector float stack.
-- Pushes the modified float vector to the vector float stack.
instructionVectorFloatReplaceAll :: State -> State
instructionVectorFloatReplaceAll = instructionVectorReplace float vectorFloat Nothing
-- |Replaces N occurrences of the top float with the second float from
-- the float stack inside of the top float vector from the vector float stack.
-- Pushes the modified float vector to the vector float stack. N is pulled from
-- the top of the int stack.
instructionVectorFloatReplaceN :: State -> State
instructionVectorFloatReplaceN = instructionVectorReplaceN float vectorFloat
-- |Replaces the first occurrence of the second float vector with the third float vector
-- inside of the first float vector from the vector float stack. Pushes the result to the
-- vector float stack.
instructionVectorFloatReplaceFirstVectorFloat :: State -> State
instructionVectorFloatReplaceFirstVectorFloat = instructionVectorReplaceVector vectorFloat (Just 1)
-- |Replaces all occurrences of the second float vector with the third float vector
-- inside of the first float vector from the vector float stack. Pushes the result to the
-- vector float stack.
instructionVectorFloatReplaceAllVectorFloat :: State -> State
instructionVectorFloatReplaceAllVectorFloat = instructionVectorReplaceVector vectorFloat Nothing
-- |Replaces N occurrences of the second float vector with the third float vector
-- inside of the first float vector from the vector float stack. Pushes the result to the
-- vector float stack. N is pulled from the top of the int stack.
instructionVectorFloatReplaceVectorFloatN :: State -> State
instructionVectorFloatReplaceVectorFloatN = instructionVectorReplaceVectorN vectorFloat
-- |Removes the first occurrence of the top float from
-- the float stack inside of the top float vector from the vector float stack.
-- Pushes the modified float vector to the vector float stack.
instructionVectorFloatRemoveFirst :: State -> State
instructionVectorFloatRemoveFirst = instructionVectorRemove float vectorFloat (Just 1)
-- |Removes the all occurrences of the top float from
-- the float stack inside of the top float vector from the vector float stack.
-- Pushes the modified float vector to the vector float stack.
instructionVectorFloatRemoveAll :: State -> State
instructionVectorFloatRemoveAll = instructionVectorRemove float vectorFloat Nothing
-- |Removes N occurrences of the top float from
-- the float stack inside of the top float vector from the vector float stack.
-- Pushes the modified float vector to the vector float stack. N is pulled
-- from the top of the int stack.
instructionVectorFloatRemoveN :: State -> State
instructionVectorFloatRemoveN = instructionVectorRemoveN float vectorFloat
-- |Removes the first occurrence of the second float vector
-- inside of the first float vector from the vector float stack. Pushes the result to the
-- vector float stack.
instructionVectorFloatRemoveFirstVectorFloat :: State -> State
instructionVectorFloatRemoveFirstVectorFloat = instructionVectorRemoveVector vectorFloat (Just 1)
-- |Removes all occurrences of the second float vector
-- inside of the first float vector from the vector float stack. Pushes the result to the
-- vector float stack.
instructionVectorFloatRemoveAllVectorFloat :: State -> State
instructionVectorFloatRemoveAllVectorFloat = instructionVectorRemoveVector vectorFloat Nothing
-- |Removes N occurrences of the second float vector
-- inside of the first float vector from the vector float stack. Pushes the result to the
-- vector float stack. N is pulled from the top of the int stack.
instructionVectorFloatRemoveNVectorFloat :: State -> State
instructionVectorFloatRemoveNVectorFloat = instructionVectorRemoveVectorN vectorFloat
-- |Iterates over the top float vector on the vector float stack, applying the top instruction of the
-- exec stack along the way.
instructionVectorFloatIterate :: State -> State
instructionVectorFloatIterate = instructionVectorIterate float vectorFloat GeneVectorFloat instructionVectorFloatIterate "instructionVectorFloatIterate"
-- |Sorts the top float vector on the vector float stack and pushes the result back to the
-- vector float stack.
instructionVectorFloatSort :: State -> State
instructionVectorFloatSort = instructionVectorSort vectorFloat
-- |Sorts the top float vector on the vector float stack, reverses it, and pushes the result back to the
-- vector float stack.
instructionVectorFloatSortReverse :: State -> State
instructionVectorFloatSortReverse = instructionVectorSortReverse vectorFloat
-- |Inserts the top float from the float stack into the top float vector from the
-- vector float stack at a specified index and pushes the result to the vector
-- float stack. The index is pulled from the top of the int stack.
instructionVectorFloatInsert :: State -> State
instructionVectorFloatInsert = instructionVectorInsert float vectorFloat
-- |Inserts the second float vector into the first float vector from the vector float stack
-- at a specified index and pushes the result to the vector float stack. The index is
-- pulled from the top of the int stack.
instructionVectorFloatInsertVectorFloat :: State -> State
instructionVectorFloatInsertVectorFloat = instructionVectorInsertVector vectorFloat
-- |Takes the mean of the top float vector and pushes the rounded float value
-- to the float stack.
instructionVectorFloatMean :: State -> State
instructionVectorFloatMean state@(State {_vectorFloat = [] : _}) = instructionVectorFuncVectorToPrim float vectorFloat retZero state
instructionVectorFloatMean state = instructionVectorFuncVectorToPrim float vectorFloat (\xs -> sum xs / fromIntegral @Int @Double (length xs)) state
-- |Takes the maximum of the top float vector and pushes the float value
-- to the float stack.
instructionVectorFloatMaximum :: State -> State
instructionVectorFloatMaximum state@(State {_vectorFloat = [] : _}) = instructionVectorFuncVectorToPrim float vectorFloat retZero state
instructionVectorFloatMaximum state = instructionVectorFuncVectorToPrim float vectorFloat maximum state
-- |Takes the minimum of the top float vector and pushes the float value
-- to the float stack.
instructionVectorFloatMinimum :: State -> State
instructionVectorFloatMinimum state@(State {_vectorFloat = [] : _ }) = instructionVectorFuncVectorToPrim float vectorFloat retZero state
instructionVectorFloatMinimum state = instructionVectorFuncVectorToPrim float vectorFloat minimum state
-- |Takes the sum of the top float vector and pushes the float value
-- to the float stack.
instructionVectorFloatSum :: State -> State
instructionVectorFloatSum state@(State {_vectorFloat = [] : _}) = instructionVectorFuncVectorToPrim float vectorFloat retZero state
instructionVectorFloatSum state = instructionVectorFuncVectorToPrim float vectorFloat sum state
-- |Takes the mode of the top float vector and pushes the float value
-- to the float stack.
instructionVectorFloatMode :: State -> State
instructionVectorFloatMode state@(State {_vectorFloat = [] : _}) = instructionVectorFuncVectorToPrim float vectorFloat retZero state
instructionVectorFloatMode state = instructionVectorFuncVectorToPrim float vectorFloat mode state
-- |Takes the 2-norm of the top float vector and pushes the rounded result to
-- the float stack.
instructionVectorFloatNorm :: State -> State -- Ends up replacing with 0 so it's good.
instructionVectorFloatNorm = instructionVectorFuncVectorToPrim float vectorFloat twoNorm
-- |Takes the cummulative mean of the float vector, rounds the results and places them floato a vector as the caluculations happen and pushes it back to the top of
-- the float vector stack.
instructionVectorFloatCummulativeMean :: State -> State
instructionVectorFloatCummulativeMean = instructionVectorFuncVectorToVector vectorFloat (\xs -> zipWith (/) (scanl1 (+) xs) [1..])
-- |Takes the cummulative sum of the float vector, places the results in a vector as the caluculations happen and pushes it back to the top of
-- the float vector stack.
instructionVectorFloatCummulativeSum :: State -> State
instructionVectorFloatCummulativeSum = instructionVectorFuncVectorToVector vectorFloat (scanl1 (+))
-- |Takes the cummulative max of the float vector, places the results in a vector as the caluculations happen and pushes it back to the top of
-- the float vector stack.
instructionVectorFloatCummulativeMax :: State -> State
instructionVectorFloatCummulativeMax = instructionVectorFuncVectorToVector vectorFloat (scanl1 max)
-- |Takes the cummulative min of the float vector, places the results in a vector as the caluculations happen and pushes it back to the top of
-- the float vector stack.
instructionVectorFloatCummulativeMin :: State -> State
instructionVectorFloatCummulativeMin = instructionVectorFuncVectorToVector vectorFloat (scanl1 min)
-- |Applies the exponential function to all indices in an float vector, rounds the result as it moves along.
instructionVectorFloatExp :: State -> State
instructionVectorFloatExp = instructionVectorFuncVectorToVector vectorFloat (map exp)
-- |Applies the log function to all indices in an float vector, rounds the result as it moves along.
instructionVectorFloatLog :: State -> State
instructionVectorFloatLog = instructionVectorFuncVectorToVector vectorFloat (map log)
-- |Applies the sin function to all indices in an float vector, rounds the result as it moves along.
instructionVectorFloatSin :: State -> State
instructionVectorFloatSin = instructionVectorFuncVectorToVector vectorFloat (map sin)
-- |Applies the cos function to all indices in an float vector, rounds the result as it moves along.
instructionVectorFloatCos :: State -> State
instructionVectorFloatCos = instructionVectorFuncVectorToVector vectorFloat (map cos)
-- |Applies the tan function to all indices in an float vector, rounds the result as it moves along.
instructionVectorFloatTan :: State -> State
instructionVectorFloatTan = instructionVectorFuncVectorToVector vectorFloat (map tan)
-- |Applies the abs function to all indices in an float vector, rounds the result as it moves along.
instructionVectorFloatAbs :: State -> State
instructionVectorFloatAbs = instructionVectorFuncVectorToVector vectorFloat (map abs)
-- |Applies the square function to all indices in an float vector, rounds the result as it moves along.
instructionVectorFloatSquare :: State -> State
instructionVectorFloatSquare = instructionVectorFuncVectorToVector vectorFloat (map (^ (2 :: Int)))
-- |Applies the cube function to all indices in an float vector, rounds the result as it moves along.
instructionVectorFloatCube :: State -> State
instructionVectorFloatCube = instructionVectorFuncVectorToVector vectorFloat (map (^ (3 :: Int)))
-- |Applies the sqrt function to all indices in an float vector, rounds the result as it moves along.
instructionVectorFloatSqrt :: State -> State
instructionVectorFloatSqrt = instructionVectorFuncVectorToVector vectorFloat (map sqrt)
allVectorFloatInstructions :: [Gene]
allVectorFloatInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,427 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.VectorIntInstructions where
import HushGP.Instructions.GenericInstructions
import HushGP.State
import HushGP.TH
import HushGP.Instructions.Utility
-- |Pops the top int vector from the int vector stack.
instructionVectorIntPop :: State -> State
instructionVectorIntPop = instructionPop vectorInt
-- |Duplicates the top int vector from the int vector stack.
instructionVectorIntDup :: State -> State
instructionVectorIntDup = instructionDup vectorInt
-- |Duplicates the top int vector from the int vector stack N times
-- based on the top int from the int stack.
instructionVectorIntDupN :: State -> State
instructionVectorIntDupN = instructionDupN vectorInt
-- |Swaps the top two int vectors from the int vector stack.
instructionVectorIntSwap :: State -> State
instructionVectorIntSwap = instructionSwap vectorInt
-- |Rotates the top three int vectors from the int vector stack.
instructionVectorIntRot :: State -> State
instructionVectorIntRot = instructionRot vectorInt
-- |Sets the vector int stack to []
instructionVectorIntFlush :: State -> State
instructionVectorIntFlush = instructionFlush vectorInt
-- |Pushes True to the bool stack if the top two int vectors from
-- the vector int stack are equal. Pushes False otherwise.
instructionVectorIntEq :: State -> State
instructionVectorIntEq = instructionEq vectorInt
-- |Calculates the size of the vector int stack and pushes that number
-- to the int stack.
instructionVectorIntStackDepth :: State -> State
instructionVectorIntStackDepth = instructionStackDepth vectorInt
-- |Moves an item from deep within the vector int stack to the top of the vector int stack based on
-- the top int from the int stack.
instructionVectorIntYank :: State -> State
instructionVectorIntYank = instructionYank vectorInt
-- |Copies an item from deep within the vector int stack to the top of the vector int stack based on
-- the top int from the int stack.
instructionVectorIntYankDup :: State -> State
instructionVectorIntYankDup = instructionYankDup vectorInt
-- |Pushes True to the bool stack if the vector int stack is empty. False if not.
instructionVectorIntIsStackEmpty :: State -> State
instructionVectorIntIsStackEmpty = instructionIsStackEmpty vectorInt
-- |Moves an item from the top of the vector int stack to deep within the vector int stack based on
-- the top int from the int stack.
instructionVectorIntShove :: State -> State
instructionVectorIntShove = instructionShove vectorInt
-- |Copies an item from the top of the vector int stack to deep within the vector int stack based on
-- the top int from the int stack.
instructionVectorIntShoveDup :: State -> State
instructionVectorIntShoveDup = instructionShoveDup vectorInt
-- |Duplicate the top N items from the vector int stack based on the top int from the int stack.
instructionVectorIntDupItems :: State -> State
instructionVectorIntDupItems = instructionDupItems vectorInt
-- |Concats the top two vectors on top of the vector int stack.
instructionVectorIntConcat :: State -> State
instructionVectorIntConcat = instructionVectorConcat vectorInt
-- |Takes the top int from the int stack and prepends it to top int vector
-- on the int vector stack.
instructionVectorIntConj :: State -> State
instructionVectorIntConj = instructionVectorConj int vectorInt
-- |Takes the top int from the int stack and appends it to top int vector
-- on the int vector stack.
instructionVectorIntConjEnd :: State -> State
instructionVectorIntConjEnd = instructionVectorConjEnd int vectorInt
-- |Takes the first N ints from the top of the int vector from the int vector
-- and pushes the result to the int vector stack. N is pulled from the top of
-- the int stack.
instructionVectorIntTakeN :: State -> State
instructionVectorIntTakeN = instructionVectorTakeN vectorInt
-- |Takes the last N ints from the top of the int vector from the int vector
-- and pushes the result to the int vector stack. N is pulled from the top of
-- the int stack.
instructionVectorIntTakeRN :: State -> State
instructionVectorIntTakeRN = instructionVectorTakeRN vectorInt
-- |Takes a sublist of the top int vector on top of the vector int stack.
-- The two ints to determine bounds are pulled from the top of the int stack.
instructionVectorIntSubVector :: State -> State
instructionVectorIntSubVector = instructionSubVector vectorInt
-- |Takes the first int from the top of the vector int stack and places
-- it on the int stack.
instructionVectorIntFirst :: State -> State
instructionVectorIntFirst = instructionVectorFirst int vectorInt
-- |Takes the first int from the top of the vector int stack and places
-- it wrapped in a list on top of the vector int stack.
instructionVectorIntFromFirstPrim :: State -> State
instructionVectorIntFromFirstPrim = instructionVectorFromFirstPrim vectorInt
-- |Takes the first int from the top of the int stack and places it
-- wrapped in a list on top of the vector int stack.
instructionVectorIntFromPrim :: State -> State
instructionVectorIntFromPrim = instructionVectorFromPrim int vectorInt
-- |Takes the last int from the top of the vector int stack and places
-- it on the int stack.
instructionVectorIntLast :: State -> State
instructionVectorIntLast = instructionVectorLast int vectorInt
-- |Takes the last int from the top int vector on the vector int stack and
-- places it on the int stack.
instructionVectorIntFromLastPrim :: State -> State
instructionVectorIntFromLastPrim = instructionVectorFromLastPrim vectorInt
-- |Takes the Nth int from the top int vector and places it onto the int stack
-- based on an int from the top of the int stack.
instructionVectorIntNth :: State -> State
instructionVectorIntNth = instructionVectorNth int vectorInt
-- |Takes the Nth int from the top int vector on the vector int stack and
-- creates a vector wrapping that Nth item, pushing it back onto the vector int stack.
-- N is the top item on the int stack.
instructionVectorIntFromNthPrim :: State -> State
instructionVectorIntFromNthPrim = instructionVectorFromNthPrim vectorInt
-- |Removes the first int from the top int vector on the vector int stack and
-- places the result back onto the vector int stack.
instructionVectorIntRest :: State -> State
instructionVectorIntRest = instructionVectorRest vectorInt
-- |Removes the last int from the top int vector on the vector int stack and
-- places the result back onto the vector int stack.
instructionVectorIntButLast :: State -> State
instructionVectorIntButLast = instructionVectorButLast vectorInt
-- |Drops the first N items from the top int vector and pushes the result
-- back to the vector int stack. N is pulled from the top of the int stack.
instructionVectorIntDrop :: State -> State
instructionVectorIntDrop = instructionVectorDrop vectorInt
-- |Drops the last N items from the top int vector and pushes the result
-- back to the vector int stack. N is pulled from the top of the int stack.
instructionVectorIntDropR :: State -> State
instructionVectorIntDropR = instructionVectorDropR vectorInt
-- |Pushes the length of the top int vector from the vector int stack
-- to the top of the int stack.
instructionVectorIntLength :: State -> State
instructionVectorIntLength = instructionLength vectorInt
-- |Reverses the top int vector from the vector int stack and pushes the
-- result to the vector int stack.
instructionVectorIntReverse :: State -> State
instructionVectorIntReverse = instructionReverse vectorInt
-- |Takes the top int vector from the vector int stack and pushes the
-- individual ints to the vector int stack.
instructionVectorIntPushAll :: State -> State
instructionVectorIntPushAll = instructionPushAll int vectorInt
-- |Makes an empty vector and pushes it to the vector int stack.
instructionVectorIntMakeEmpty :: State -> State
instructionVectorIntMakeEmpty = instructionVectorMakeEmpty vectorInt
-- |Checks if the top int vector from the vector int stack is empty.
-- Pushes True if the int vector is empty to the bool stack. False otherwise.
instructionVectorIntIsEmpty :: State -> State
instructionVectorIntIsEmpty = instructionVectorIsEmpty vectorInt
-- |If the top int vector from the vector int stack contains the top int from the int
-- stack, pushes True to the bool stack and pushes False otherwise.
instructionVectorIntContains :: State -> State
instructionVectorIntContains = instructionVectorContains int vectorInt
-- |If the second to top int vector can be found within the first int vector from the
-- vector int stack, pushes True to the bool stack if is found, else False.
instructionVectorIntContainsVectorInt :: State -> State
instructionVectorIntContainsVectorInt = instructionVectorContainsVector vectorInt
-- |Finds the first index of the top int in the int stack inside of the
-- top int vector from the vector int stack and pushes the result to the int stack.
instructionVectorIntIndexOf :: State -> State
instructionVectorIntIndexOf = instructionVectorIndexOf int vectorInt
-- |Searches and pushes the index of the second int vector inside of the first
-- int vector to the int stack from the vector int stack. Pushes -1 if not found.
instructionVectorIntIndexOfVectorInt :: State -> State
instructionVectorIntIndexOfVectorInt = instructionVectorIndexOfVector vectorInt
-- |Finds the amount of times the top int on the int stack occurs inside of
-- the top int vector from the vector int stack and pushes the result to the
-- int stack.
instructionVectorIntOccurrencesOf :: State -> State
instructionVectorIntOccurrencesOf = instructionVectorOccurrencesOf int vectorInt
-- |Counts the amount of occurrences of the second int vector within the first
-- int vector. Pushes the result to the int stack.
instructionVectorIntOccurrencesOfVectorInt :: State -> State
instructionVectorIntOccurrencesOfVectorInt = instructionVectorOccurrencesOfVector vectorInt
-- |Splits the top int vector from the vector int stack into lists of size one and pushes
-- the result back one the vector int stack.
instructionVectorIntParseToInt :: State -> State
instructionVectorIntParseToInt = instructionVectorParseToPrim vectorInt
-- |Sets the Nth index inside of the top int vector from the vector int stack to the
-- top value from the primitive stack. N is pulled from the top of the int stack.
instructionVectorIntSetNth :: State -> State
instructionVectorIntSetNth = instructionVectorSetNth int vectorInt
-- |Splits the int vector on top of the vector int stack with the int from the top
-- of the int stack and pushes the result to the original vector stack.
instructionVectorIntSplitOn :: State -> State
instructionVectorIntSplitOn = instructionVectorSplitOn int vectorInt
-- |Splits the first int vector based on the second int vector from the vector
-- int stack and pushes the result to the vector int stack.
instructionVectorIntSplitOnVectorInt :: State -> State
instructionVectorIntSplitOnVectorInt = instructionVectorSplitOnVector vectorInt
-- |Replaces the first occurrence of the top int with the second int from
-- the int stack inside of the top int vector from the vector int stack.
-- Pushes the modified int vector to the vector int stack.
instructionVectorIntReplaceFirst :: State -> State
instructionVectorIntReplaceFirst = instructionVectorReplace int vectorInt (Just 1)
-- |Replaces all occurrences of the top int with the second int from
-- the int stack inside of the top int vector from the vector int stack.
-- Pushes the modified int vector to the vector int stack.
instructionVectorIntReplaceAll :: State -> State
instructionVectorIntReplaceAll = instructionVectorReplace int vectorInt Nothing
-- |Replaces N occurrences of the top int with the second int from
-- the int stack inside of the top int vector from the vector int stack.
-- Pushes the modified int vector to the vector int stack. N is pulled from
-- the top of the int stack.
instructionVectorIntReplaceN :: State -> State
instructionVectorIntReplaceN = instructionVectorReplaceN int vectorInt
-- |Replaces the first occurrence of the second int vector with the third int vector
-- inside of the first int vector from the vector int stack. Pushes the result to the
-- vector int stack.
instructionVectorIntReplaceFirstVectorInt :: State -> State
instructionVectorIntReplaceFirstVectorInt = instructionVectorReplaceVector vectorInt (Just 1)
-- |Replaces all occurrences of the second int vector with the third int vector
-- inside of the first int vector from the vector int stack. Pushes the result to the
-- vector int stack.
instructionVectorIntReplaceAllVectorInt :: State -> State
instructionVectorIntReplaceAllVectorInt = instructionVectorReplaceVector vectorInt Nothing
-- |Replaces N occurrences of the second int vector with the third int vector
-- inside of the first int vector from the vector int stack. Pushes the result to the
-- vector int stack. N is pulled from the top of the int stack.
instructionVectorIntReplaceVectorIntN :: State -> State
instructionVectorIntReplaceVectorIntN = instructionVectorReplaceVectorN vectorInt
-- |Removes the first occurrence of the top int from
-- the int stack inside of the top int vector from the vector int stack.
-- Pushes the modified int vector to the vector int stack.
instructionVectorIntRemoveFirst :: State -> State
instructionVectorIntRemoveFirst = instructionVectorRemove int vectorInt (Just 1)
-- |Removes the all occurrences of the top int from
-- the int stack inside of the top int vector from the vector int stack.
-- Pushes the modified int vector to the vector int stack.
instructionVectorIntRemoveAll :: State -> State
instructionVectorIntRemoveAll = instructionVectorRemove int vectorInt Nothing
-- |Removes N occurrences of the top int from
-- the int stack inside of the top int vector from the vector int stack.
-- Pushes the modified int vector to the vector int stack. N is pulled
-- from the top of the int stack.
instructionVectorIntRemoveN :: State -> State
instructionVectorIntRemoveN = instructionVectorRemoveN int vectorInt
-- |Removes the first occurrence of the second int vector
-- inside of the first int vector from the vector int stack. Pushes the result to the
-- vector int stack.
instructionVectorIntRemoveFirstVectorInt :: State -> State
instructionVectorIntRemoveFirstVectorInt = instructionVectorRemoveVector vectorInt (Just 1)
-- |Removes all occurrences of the second int vector
-- inside of the first int vector from the vector int stack. Pushes the result to the
-- vector int stack.
instructionVectorIntRemoveAllVectorInt :: State -> State
instructionVectorIntRemoveAllVectorInt = instructionVectorRemoveVector vectorInt Nothing
-- |Removes N occurrences of the second int vector
-- inside of the first int vector from the vector int stack. Pushes the result to the
-- vector int stack. N is pulled from the top of the int stack.
instructionVectorIntRemoveNVectorInt :: State -> State
instructionVectorIntRemoveNVectorInt = instructionVectorRemoveVectorN vectorInt
-- |Iterates over the top int vector on the vector int stack, applying the top instruction of the
-- exec stack along the way.
instructionVectorIntIterate :: State -> State
instructionVectorIntIterate = instructionVectorIterate int vectorInt GeneVectorInt instructionVectorIntIterate "instructionVectorIntIterate"
-- |Sorts the top int vector on the vector int stack and pushes the result back to the
-- vector int stack.
instructionVectorIntSort :: State -> State
instructionVectorIntSort = instructionVectorSort vectorInt
-- |Sorts the top int vector on the vector int stack, reverses it, and pushes the result back to the
-- vector int stack.
instructionVectorIntSortReverse :: State -> State
instructionVectorIntSortReverse = instructionVectorSortReverse vectorInt
-- |Inserts the top int from the int stack into the top int vector from the
-- vector int stack at a specified index and pushes the result to the vector
-- int stack. The index is pulled from the top of the int stack.
instructionVectorIntInsert :: State -> State
instructionVectorIntInsert = instructionVectorInsert int vectorInt
-- |Inserts the second int vector into the first int vector from the vector int stack
-- at a specified index and pushes the result to the vector int stack. The index is
-- pulled from the top of the int stack.
instructionVectorIntInsertVectorInt :: State -> State
instructionVectorIntInsertVectorInt = instructionVectorInsertVector vectorInt
-- |Takes the mean of the top int vector and pushes the rounded int value
-- to the int stack.
instructionVectorIntMean :: State -> State
instructionVectorIntMean state@(State {_vectorInt = [] : _}) = instructionVectorFuncVectorToPrim int vectorInt retZero state
instructionVectorIntMean state = instructionVectorFuncVectorToPrim int vectorInt (\xs -> round $ sum (map (fromIntegral @Integer @Double) xs) / fromIntegral @Int @Double (length xs)) state
-- |Takes the maximum of the top int vector and pushes the int value
-- to the int stack.
instructionVectorIntMaximum :: State -> State
instructionVectorIntMaximum state@(State {_vectorInt = [] : _}) = instructionVectorFuncVectorToPrim int vectorInt retZero state
instructionVectorIntMaximum state = instructionVectorFuncVectorToPrim int vectorInt maximum state
-- |Takes the minimum of the top int vector and pushes the int value
-- to the int stack.
instructionVectorIntMinimum :: State -> State
instructionVectorIntMinimum state@(State {_vectorInt = [] : _ }) = instructionVectorFuncVectorToPrim int vectorInt retZero state
instructionVectorIntMinimum state = instructionVectorFuncVectorToPrim int vectorInt minimum state
-- |Takes the sum of the top int vector and pushes the int value
-- to the int stack.
instructionVectorIntSum :: State -> State
instructionVectorIntSum state@(State {_vectorInt = [] : _}) = instructionVectorFuncVectorToPrim int vectorInt retZero state
instructionVectorIntSum state = instructionVectorFuncVectorToPrim int vectorInt sum state
-- |Takes the mode of the top int vector and pushes the int value
-- to the int stack.
instructionVectorIntMode :: State -> State
instructionVectorIntMode state@(State {_vectorInt = [] : _}) = instructionVectorFuncVectorToPrim int vectorInt retZero state
instructionVectorIntMode state = instructionVectorFuncVectorToPrim int vectorInt mode state
-- |Takes the 2-norm of the top int vector and pushes the rounded result to
-- the int stack.
instructionVectorIntNorm :: State -> State -- Ends up replacing with 0 so it's good.
instructionVectorIntNorm = instructionVectorFuncVectorToPrim int vectorInt (round . twoNorm . map (fromIntegral @Integer @Double))
-- |Takes the cummulative mean of the int vector, rounds the results and places them into a vector as the caluculations happen and pushes it back to the top of
-- the int vector stack.
instructionVectorIntCummulativeMean :: State -> State
instructionVectorIntCummulativeMean = instructionVectorFuncVectorToVector vectorInt (\xs -> zipWith div (scanl1 (+) xs) [1..])
-- |Takes the cummulative sum of the int vector, places the results in a vector as the caluculations happen and pushes it back to the top of
-- the int vector stack.
instructionVectorIntCummulativeSum :: State -> State
instructionVectorIntCummulativeSum = instructionVectorFuncVectorToVector vectorInt (scanl1 (+))
-- |Takes the cummulative max of the int vector, places the results in a vector as the caluculations happen and pushes it back to the top of
-- the int vector stack.
instructionVectorIntCummulativeMax :: State -> State
instructionVectorIntCummulativeMax = instructionVectorFuncVectorToVector vectorInt (scanl1 max)
-- |Takes the cummulative min of the int vector, places the results in a vector as the caluculations happen and pushes it back to the top of
-- the int vector stack.
instructionVectorIntCummulativeMin :: State -> State
instructionVectorIntCummulativeMin = instructionVectorFuncVectorToVector vectorInt (scanl1 min)
-- |Applies the exponential function to all indices in an int vector, rounds the result as it moves along.
instructionVectorIntExp :: State -> State
instructionVectorIntExp = instructionVectorFuncVectorToVector vectorInt (map (round . exp . fromIntegral @Integer @Double))
-- |Applies the log function to all indices in an int vector, rounds the result as it moves along.
instructionVectorIntLog :: State -> State
instructionVectorIntLog = instructionVectorFuncVectorToVector vectorInt (map (round . log . fromIntegral @Integer @Double))
-- |Applies the sin function to all indices in an int vector, rounds the result as it moves along.
instructionVectorIntSin :: State -> State
instructionVectorIntSin = instructionVectorFuncVectorToVector vectorInt (map (round . sin . fromIntegral @Integer @Double))
-- |Applies the cos function to all indices in an int vector, rounds the result as it moves along.
instructionVectorIntCos :: State -> State
instructionVectorIntCos = instructionVectorFuncVectorToVector vectorInt (map (round . cos . fromIntegral @Integer @Double))
-- |Applies the tan function to all indices in an int vector, rounds the result as it moves along.
instructionVectorIntTan :: State -> State
instructionVectorIntTan = instructionVectorFuncVectorToVector vectorInt (map (round . tan . fromIntegral @Integer @Double))
-- |Applies the abs function to all indices in an int vector, rounds the result as it moves along.
instructionVectorIntAbs :: State -> State
instructionVectorIntAbs = instructionVectorFuncVectorToVector vectorInt (map (round . abs . fromIntegral @Integer @Double))
-- |Applies the square function to all indices in an int vector, rounds the result as it moves along.
instructionVectorIntSquare :: State -> State
instructionVectorIntSquare = instructionVectorFuncVectorToVector vectorInt (map (round . (^ (2 :: Int)) . fromIntegral @Integer @Double))
-- |Applies the cube function to all indices in an int vector, rounds the result as it moves along.
instructionVectorIntCube :: State -> State
instructionVectorIntCube = instructionVectorFuncVectorToVector vectorInt (map (round . (^ (3 :: Int)) . fromIntegral @Integer @Double))
-- |Applies the sqrt function to all indices in an int vector, rounds the result as it moves along.
instructionVectorIntSqrt :: State -> State
instructionVectorIntSqrt = instructionVectorFuncVectorToVector vectorInt (map (round . sqrt . fromIntegral @Integer @Double))
allVectorIntInstructions :: [Gene]
allVectorIntInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,335 @@
{-# LANGUAGE TemplateHaskell #-}
module HushGP.Instructions.VectorStringInstructions where
import HushGP.State
import HushGP.Instructions.GenericInstructions
import HushGP.TH
-- |Pops the top string vector from the string vector stack.
instructionVectorStringPop :: State -> State
instructionVectorStringPop = instructionPop vectorString
-- |Duplicates the top string vector from the string vector stack.
instructionVectorStringDup :: State -> State
instructionVectorStringDup = instructionDup vectorString
-- |Duplicates the top string vector from the string vector stack N times
-- based on the top int from the int stack.
instructionVectorStringDupN :: State -> State
instructionVectorStringDupN = instructionDupN vectorString
-- |Swaps the top two string vectors from the string vector stack.
instructionVectorStringSwap :: State -> State
instructionVectorStringSwap = instructionSwap vectorString
-- |Rotates the top three string vectors from the string vector stack.
instructionVectorStringRot :: State -> State
instructionVectorStringRot = instructionRot vectorString
-- |Sets the vector string stack to []
instructionVectorStringFlush :: State -> State
instructionVectorStringFlush = instructionFlush vectorString
-- |Pushes True to the bool stack if the top two string vectors from
-- the vector string stack are equal. Pushes False otherwise.
instructionVectorStringEq :: State -> State
instructionVectorStringEq = instructionEq vectorString
-- |Calculates the size of the vector string stack and pushes that number
-- to the int stack.
instructionVectorStringStackDepth :: State -> State
instructionVectorStringStackDepth = instructionStackDepth vectorString
-- |Moves an item from deep within the vector string stack to the top of the vector string stack based on
-- the top int from the int stack.
instructionVectorStringYank :: State -> State
instructionVectorStringYank = instructionYank vectorString
-- |Copies an item from deep within the vector string stack to the top of the vector string stack based on
-- the top int from the int stack.
instructionVectorStringYankDup :: State -> State
instructionVectorStringYankDup = instructionYankDup vectorString
-- |Pushes True to the bool stack if the vector string stack is empty. False if not.
instructionVectorStringIsStackEmpty :: State -> State
instructionVectorStringIsStackEmpty = instructionIsStackEmpty vectorString
-- |Moves an item from the top of the vector string stack to deep within the vector string stack based on
-- the top int from the int stack.
instructionVectorStringShove :: State -> State
instructionVectorStringShove = instructionShove vectorString
-- |Copies an item from the top of the vector string stack to deep within the vector string stack based on
-- the top int from the int stack.
instructionVectorStringShoveDup :: State -> State
instructionVectorStringShoveDup = instructionShoveDup vectorString
-- |Duplicate the top N items from the vector string stack based on the top int from the int stack.
instructionVectorStringDupItems :: State -> State
instructionVectorStringDupItems = instructionDupItems vectorString
-- |Concats the top two vectors on top of the vector string stack.
instructionVectorStringConcat :: State -> State
instructionVectorStringConcat = instructionVectorConcat vectorString
-- |Takes the top string from the string stack and prepends it to top string vector
-- on the string vector stack.
instructionVectorStringConj :: State -> State
instructionVectorStringConj = instructionVectorConj string vectorString
-- |Takes the top string from the string stack and appends it to top string vector
-- on the string vector stack.
instructionVectorStringConjEnd :: State -> State
instructionVectorStringConjEnd = instructionVectorConjEnd string vectorString
-- |Takes the first N strings from the top of the string vector from the string vector
-- and pushes the result to the string vector stack. N is pulled from the top of
-- the int stack.
instructionVectorStringTakeN :: State -> State
instructionVectorStringTakeN = instructionVectorTakeN vectorString
-- |Takes the last N strings from the top of the string vector from the string vector
-- and pushes the result to the string vector stack. N is pulled from the top of
-- the int stack.
instructionVectorStringTakeRN :: State -> State
instructionVectorStringTakeRN = instructionVectorTakeRN vectorString
-- |Takes a sublist of the top string vector on top of the vector string stack.
-- The two ints to determine bounds are pulled from the top of the int stack.
instructionVectorStringSubVector :: State -> State
instructionVectorStringSubVector = instructionSubVector vectorString
-- |Takes the first string from the top of the vector string stack and places
-- it on the string stack.
instructionVectorStringFirst :: State -> State
instructionVectorStringFirst = instructionVectorFirst string vectorString
-- |Takes the first string from the top of the vector string stack and places
-- it wrapped in a list on top of the vector string stack.
instructionVectorStringFromFirstPrim :: State -> State
instructionVectorStringFromFirstPrim = instructionVectorFromFirstPrim vectorString
-- |Takes the first string from the top of the string stack and places it
-- wrapped in a list on top of the vector string stack.
instructionVectorStringFromPrim :: State -> State
instructionVectorStringFromPrim = instructionVectorFromPrim string vectorString
-- |Takes the last string from the top of the vector string stack and places
-- it on the string stack.
instructionVectorStringLast :: State -> State
instructionVectorStringLast = instructionVectorLast string vectorString
-- |Takes the last string from the top string vector on the vector string stack and
-- places it on the string stack.
instructionVectorStringFromLastPrim :: State -> State
instructionVectorStringFromLastPrim = instructionVectorFromLastPrim vectorString
-- |Takes the Nth string from the top string vector and places it onto the string stack
-- based on an int from the top of the int stack.
instructionVectorStringNth :: State -> State
instructionVectorStringNth = instructionVectorNth string vectorString
-- |Takes the Nth string from the top string vector on the vector string stack and
-- creates a vector wrapping that Nth item, pushing it back onto the vector string stack.
-- N is the top item on the int stack.
instructionVectorStringFromNthPrim :: State -> State
instructionVectorStringFromNthPrim = instructionVectorFromNthPrim vectorString
-- |Removes the first string from the top string vector on the vector string stack and
-- places the result back onto the vector string stack.
instructionVectorStringRest :: State -> State
instructionVectorStringRest = instructionVectorRest vectorString
-- |Removes the last string from the top string vector on the vector string stack and
-- places the result back onto the vector string stack.
instructionVectorStringButLast :: State -> State
instructionVectorStringButLast = instructionVectorButLast vectorString
-- |Drops the first N items from the top string vector and pushes the result
-- back to the vector string stack. N is pulled from the top of the int stack.
instructionVectorStringDrop :: State -> State
instructionVectorStringDrop = instructionVectorDrop vectorString
-- |Drops the last N items from the top string vector and pushes the result
-- back to the vector string stack. N is pulled from the top of the int stack.
instructionVectorStringDropR :: State -> State
instructionVectorStringDropR = instructionVectorDropR vectorString
-- |Pushes the length of the top string vector from the vector string stack
-- to the top of the int stack.
instructionVectorStringLength :: State -> State
instructionVectorStringLength = instructionLength vectorString
-- |Reverses the top string vector from the vector string stack and pushes the
-- result to the vector string stack.
instructionVectorStringReverse :: State -> State
instructionVectorStringReverse = instructionReverse vectorString
-- |Takes the top string vector from the vector string stack and pushes the
-- individual strings to the vector string stack.
instructionVectorStringPushAll :: State -> State
instructionVectorStringPushAll = instructionPushAll string vectorString
-- |Makes an empty vector and pushes it to the vector string stack.
instructionVectorStringMakeEmpty :: State -> State
instructionVectorStringMakeEmpty = instructionVectorMakeEmpty vectorString
-- |Checks if the top string vector from the vector string stack is empty.
-- Pushes True if the string vector is empty to the bool stack. False otherwise.
instructionVectorStringIsEmpty :: State -> State
instructionVectorStringIsEmpty = instructionVectorIsEmpty vectorString
-- |If the top string vector from the vector string stack contains the top string from the string
-- stack, pushes True to the bool stack and pushes False otherwise.
instructionVectorStringContains :: State -> State
instructionVectorStringContains = instructionVectorContains string vectorString
-- |If the second to top string vector can be found within the first string vector from the
-- vector string stack, pushes True to the bool stack if is found, else False.
instructionVectorStringContainsVectorString :: State -> State
instructionVectorStringContainsVectorString = instructionVectorContainsVector vectorString
-- |Finds the first index of the top string in the string stack inside of the
-- top string vector from the vector string stack and pushes the result to the int stack.
instructionVectorStringIndexOf :: State -> State
instructionVectorStringIndexOf = instructionVectorIndexOf string vectorString
-- |Searches and pushes the index of the second string vector inside of the first
-- string vector to the int stack from the vector string stack. Pushes -1 if not found.
instructionVectorStringIndexOfVectorString :: State -> State
instructionVectorStringIndexOfVectorString = instructionVectorIndexOfVector vectorString
-- |Finds the amount of times the top string on the string stack occurs inside of
-- the top string vector from the vector string stack and pushes the result to the
-- int stack.
instructionVectorStringOccurrencesOf :: State -> State
instructionVectorStringOccurrencesOf = instructionVectorOccurrencesOf string vectorString
-- |Counts the amount of occurrences of the second string vector within the first
-- string vector. Pushes the result to the int stack.
instructionVectorStringOccurrencesOfVectorString :: State -> State
instructionVectorStringOccurrencesOfVectorString = instructionVectorOccurrencesOfVector vectorString
-- |Splits the top string vector from the vector string stack into lists of size one and pushes
-- the result back one the vector string stack.
instructionVectorStringParseToString :: State -> State
instructionVectorStringParseToString = instructionVectorParseToPrim vectorString
-- |Sets the Nth index inside of the top string vector from the vector string stack to the
-- top value from the primitive stack. N is pulled from the top of the int stack.
instructionVectorStringSetNth :: State -> State
instructionVectorStringSetNth = instructionVectorSetNth string vectorString
-- |Splits the string vector on top of the vector string stack with the string from the top
-- of the string stack and pushes the result to the original vector stack.
instructionVectorStringSplitOn :: State -> State
instructionVectorStringSplitOn = instructionVectorSplitOn string vectorString
-- |Splits the first string vector based on the second string vector from the vector
-- string stack and pushes the result to the vector string stack.
instructionVectorStringSplitOnVectorString :: State -> State
instructionVectorStringSplitOnVectorString = instructionVectorSplitOnVector vectorString
-- |Replaces the first occurrence of the top string with the second string from
-- the string stack inside of the top string vector from the vector string stack.
-- Pushes the modified string vector to the vector string stack.
instructionVectorStringReplaceFirst :: State -> State
instructionVectorStringReplaceFirst = instructionVectorReplace string vectorString (Just 1)
-- |Replaces all occurrences of the top string with the second string from
-- the string stack inside of the top string vector from the vector string stack.
-- Pushes the modified string vector to the vector string stack.
instructionVectorStringReplaceAll :: State -> State
instructionVectorStringReplaceAll = instructionVectorReplace string vectorString Nothing
-- |Replaces N occurrences of the top string with the second string from
-- the string stack inside of the top string vector from the vector string stack.
-- Pushes the modified string vector to the vector string stack. N is pulled from
-- the top of the int stack.
instructionVectorStringReplaceN :: State -> State
instructionVectorStringReplaceN = instructionVectorReplaceN string vectorString
-- |Replaces the first occurrence of the second string vector with the third string vector
-- inside of the first string vector from the vector string stack. Pushes the result to the
-- vector string stack.
instructionVectorStringReplaceFirstVectorString :: State -> State
instructionVectorStringReplaceFirstVectorString = instructionVectorReplaceVector vectorString (Just 1)
-- |Replaces all occurrences of the second string vector with the third string vector
-- inside of the first string vector from the vector string stack. Pushes the result to the
-- vector string stack.
instructionVectorStringReplaceAllVectorString :: State -> State
instructionVectorStringReplaceAllVectorString = instructionVectorReplaceVector vectorString Nothing
-- |Replaces N occurrences of the second string vector with the third string vector
-- inside of the first string vector from the vector string stack. Pushes the result to the
-- vector string stack. N is pulled from the top of the int stack.
instructionVectorStringReplaceVectorStringN :: State -> State
instructionVectorStringReplaceVectorStringN = instructionVectorReplaceVectorN vectorString
-- |Removes the first occurrence of the top string from
-- the string stack inside of the top string vector from the vector string stack.
-- Pushes the modified string vector to the vector string stack.
instructionVectorStringRemoveFirst :: State -> State
instructionVectorStringRemoveFirst = instructionVectorRemove string vectorString (Just 1)
-- |Removes the all occurrences of the top string from
-- the string stack inside of the top string vector from the vector string stack.
-- Pushes the modified string vector to the vector string stack.
instructionVectorStringRemoveAll :: State -> State
instructionVectorStringRemoveAll = instructionVectorRemove string vectorString Nothing
-- |Removes N occurrences of the top string from
-- the string stack inside of the top string vector from the vector string stack.
-- Pushes the modified string vector to the vector string stack. N is pulled
-- from the top of the int stack.
instructionVectorStringRemoveN :: State -> State
instructionVectorStringRemoveN = instructionVectorRemoveN string vectorString
-- |Removes the first occurrence of the second string vector
-- inside of the first string vector from the vector string stack. Pushes the result to the
-- vector string stack.
instructionVectorStringRemoveFirstVectorString :: State -> State
instructionVectorStringRemoveFirstVectorString = instructionVectorRemoveVector vectorString (Just 1)
-- |Removes all occurrences of the second string vector
-- inside of the first string vector from the vector string stack. Pushes the result to the
-- vector string stack.
instructionVectorStringRemoveAllVectorString :: State -> State
instructionVectorStringRemoveAllVectorString = instructionVectorRemoveVector vectorString Nothing
-- |Removes N occurrences of the second string vector
-- inside of the first string vector from the vector string stack. Pushes the result to the
-- vector string stack. N is pulled from the top of the int stack.
instructionVectorStringRemoveNVectorString :: State -> State
instructionVectorStringRemoveNVectorString = instructionVectorRemoveVectorN vectorString
-- |Iterates over the top string vector on the vector string stack, applying the top instruction of the
-- exec stack along the way.
instructionVectorStringIterate :: State -> State
instructionVectorStringIterate = instructionVectorIterate string vectorString GeneVectorString instructionVectorStringIterate "instructionVectorStringIterate"
-- |Sorts the top string vector on the vector string stack and pushes the result back to the
-- vector string stack.
instructionVectorStringSort :: State -> State
instructionVectorStringSort = instructionVectorSort vectorString
-- |Sorts the top string vector on the vector string stack, reverses it, and pushes the result back to the
-- vector string stack.
instructionVectorStringSortReverse :: State -> State
instructionVectorStringSortReverse = instructionVectorSortReverse vectorString
-- |Inserts the top string from the string stack into the top string vector from the
-- vector string stack at a specified index and pushes the result to the vector
-- string stack. The index is pulled from the top of the int stack.
instructionVectorStringInsert :: State -> State
instructionVectorStringInsert = instructionVectorInsert string vectorString
-- |Inserts the second string vector into the first string vector from the vector string stack
-- at a specified index and pushes the result to the vector string stack. The index is
-- pulled from the top of the int stack.
instructionVectorStringInsertVectorString :: State -> State
instructionVectorStringInsertVectorString = instructionVectorInsertVector vectorString
allVectorStringInstructions :: [Gene]
allVectorStringInstructions = map StateFunc ($(functionExtractor "instruction"))

View File

@ -0,0 +1,122 @@
module HushGP.Problems.IntegerRegression where
import Data.List
import Data.Map qualified as Map
import HushGP.State
import HushGP.Instructions
import HushGP.GP.PushArgs
import HushGP.GP.PushData
import HushGP.Genome
import HushGP.Push
import HushGP.Instructions.Utility
import HushGP.GP
testPlushy :: [Gene]
testPlushy = [
PlaceInput 0,
GeneInt 0,
StateFunc (instructionIntAdd, "instructionIntAdd")
-- GeneFloat 3.2
]
intSolutionPlushy :: [Gene]
intSolutionPlushy =
[ PlaceInput 0
, PlaceInput 0
, PlaceInput 0
, StateFunc (instructionIntMul, "instructionIntMul")
, StateFunc (instructionIntMul, "instructionIntMul")
-- , GeneInt 2
-- , PlaceInput 0
, GeneBool True -- A useless gene
-- , StateFunc (instructionIntMul, "instructionIntMul")
-- , GeneInt 6
-- , StateFunc (instructionIntAdd, "instructionIntAdd")
-- , StateFunc (instructionIntAdd, "instructionIntAdd")
-- , GeneInt 5 -- Also a useless gene
, GeneFloat 4.3
, GeneString "hello"
]
-- | The target function for this run. The function the gp
-- is trying to evolve.
targetFunction :: Integer -> Integer
-- targetFunction x = (x * x * x) + (2 * x) + 6
targetFunction x = (x * x * x) + (2 * x)
-- targetFunction x = x * x * x
-- | The training data for the model.
intTrainData :: [PushData]
intTrainData = map (\num -> PushData {
_inputData = [GeneInt num],
_outputData = (GeneInt . targetFunction) num,
_downsampleIndex = Nothing,
_caseDistances = Nothing})
[-10..10]
-- | The testing data for the model.
intTestData :: [PushData]
intTestData = map (\num -> PushData {
_inputData = [GeneInt num],
_outputData = (GeneInt . targetFunction) num,
_downsampleIndex = Nothing,
_caseDistances = Nothing})
([-20..(-11)] <> [11..21])
-- | The instructions used in the evolutionary run.
runInstructions :: [Gene]
runInstructions =
[
PlaceInput 0,
Close,
GeneInt 1,
GeneInt 0
]
<> allIntInstructions
-- | Takes the head of the stack and returns it. If there is no head, returns an
-- error amount.
errorHead :: [Integer] -> Integer
errorHead xs =
case uncons xs of
Just (x, _) -> x
_ -> 100000000 -- Make this a variable for later?
-- | Loads a plushy and a list of genes into the input state.
loadState :: PushArgs -> [Gene] -> [Gene] -> State
loadState pushArgs plushy vals =
(loadProgram (plushyToPush pushArgs plushy) emptyState){_input = Map.fromList (zip [0..] vals)}
-- | The error function for a single set of inputs and outputs.
intErrorFunction :: PushArgs -> [PushData] -> [Gene] -> [Double]
intErrorFunction pushArgs pushData plushy =
map abs $
zipWith (-)
(map ((fromIntegral @Integer @Double . (errorHead . _int) . interpretExec) . loadState pushArgs plushy)
(extractField inputData pushData)) (map (fromIntegral @Integer @Double . extractGeneInt) (extractField outputData pushData))
intPushArgs :: PushArgs
intPushArgs = defaultPushArgs
{
instructionList = runInstructions,
errorFunction = intErrorFunction,
trainingData = intTrainData,
testingData = intTestData,
maxGenerations = 200,
populationSize = 100,
maxInitialPlushySize = 100,
stepLimit = 200,
parentSelectionAlgo = "lexicase",
tournamentSize = 5,
umadRate = 0.6,
variation = [("umad", 1.0), ("crossover", 0.0)],
elitism = False,
enableDownsampling = False,
downsampleRate = 0.5,
simplificationVerbose = True,
simplificationMaxAmt = 4,
simplificationSteps = 200
}
main :: IO ()
main = gpLoop intPushArgs

80
src/HushGP/Push.hs Normal file
View File

@ -0,0 +1,80 @@
module HushGP.Push where
import Control.Lens
import Data.Map qualified as Map
import HushGP.State
-- import Debug.Trace (trace, traceStack)
-- Each core func should be: (State -> State -> State)
-- but each core function can use abstract helper functions.
-- That is more efficient than checking length.
-- Everntually, this can be part of the apply func to state helpers,
-- which should take the number and type of parameter they have.
-- This is one of the push genome functions itself, not infrastructure.
-- Optionally, split this off into independent functions
-- instructionParameterLoad :: State -> State
-- instructionParameterLoad state@(State {_parameter = (p : _)}) = case p of
-- (GeneInt val) -> state & int .~ val : view int state
-- (GeneFloat val) -> state & float .~ val : view float state
-- (GeneBool val) -> state & bool .~ val : view bool state
-- (GeneString val) -> state & string .~ val : view string state
-- (GeneChar val) -> state & char .~ val : view char state
-- (GeneVectorInt val) -> state & vectorInt .~ val : view vectorInt state
-- (GeneVectorFloat val) -> state & vectorFloat .~ val : view vectorFloat state
-- (GeneVectorBool val) -> state & vectorBool .~ val : view vectorBool state
-- (GeneVectorString val) -> state & vectorString .~ val : view vectorString state
-- (GeneVectorChar val) -> state & vectorChar .~ val : view vectorChar state
-- (StateFunc _) -> undefined
-- (PlaceInput _) -> undefined
-- Close -> undefined
-- (Block xs) -> state & exec .~ xs <> view exec state
-- instructionParameterLoad state = state
-- | Loads a genome into the exec stack
loadProgram :: [Gene] -> State -> State
loadProgram newstack state = state & exec .~ newstack
-- | Takes a Push state, and generates the next push state via:
-- If the first item on the EXEC stack is a single instruction
-- then pop it and execute it.
-- Else if the first item on the EXEC stack is a literal
-- then pop it and push it onto the appropriate stack.
-- Else (the first item must be a list) pop it and push all of the
-- items that it contains back onto the EXEC stack individually,
-- in reverse order (so that the item that was first in the list
-- ends up on top).
-- The empty-stack safety of interpretExec on empty stacks depends on the functions it calls.
interpretExec :: State -> State
interpretExec state@(State {_exec = e : es}) =
case e of
(GeneInt val) -> interpretExec (state & exec .~ es & int .~ val : view int state)
(GeneFloat val) -> interpretExec (state & exec .~ es & float .~ val : view float state)
(GeneBool val) -> interpretExec (state & exec .~ es & bool .~ val : view bool state)
(GeneString val) -> interpretExec (state & exec .~ es & string .~ val : view string state)
(GeneChar val) -> interpretExec (state & exec .~ es & char .~ val : view char state)
(GeneVectorInt val) -> interpretExec (state & exec .~ es & vectorInt .~ val : view vectorInt state)
(GeneVectorFloat val) -> interpretExec (state & exec .~ es & vectorFloat .~ val : view vectorFloat state)
(GeneVectorBool val) -> interpretExec (state & exec .~ es & vectorBool .~ val : view vectorBool state)
(GeneVectorString val) -> interpretExec (state & exec .~ es & vectorString .~ val : view vectorString state)
(GeneVectorChar val) -> interpretExec (state & exec .~ es & vectorChar .~ val : view vectorChar state)
(StateFunc (func, _)) -> interpretExec $ func state {_exec = es}
(Block block) -> interpretExec (state {_exec = block ++ es})
(PlaceInput val) -> interpretExec (state {_exec = (view input state Map.! val) : es})
(GeneIntERC (val, _)) -> interpretExec (state & exec .~ es & int .~ val : view int state)
(GeneFloatERC (val, _)) -> interpretExec (state & exec .~ es & float .~ val : view float state)
(GeneBoolERC (val, _)) -> interpretExec (state & exec .~ es & bool .~ val : view bool state)
(GeneStringERC (val, _)) -> interpretExec (state & exec .~ es & string .~ val : view string state)
(GeneCharERC (val, _)) -> interpretExec (state & exec .~ es & char .~ val : view char state)
(GeneVectorIntERC (val, _)) -> interpretExec (state & exec .~ es & vectorInt .~ val : view vectorInt state)
(GeneVectorFloatERC (val, _)) -> interpretExec (state & exec .~ es & vectorFloat .~ val : view vectorFloat state)
(GeneVectorBoolERC (val, _)) -> interpretExec (state & exec .~ es & vectorBool .~ val : view vectorBool state)
(GeneVectorStringERC (val, _)) -> interpretExec (state & exec .~ es & vectorString .~ val : view vectorString state)
(GeneVectorCharERC (val, _)) -> interpretExec (state & exec .~ es & vectorChar .~ val : view vectorChar state)
Close -> error "Error: Close found in exec stack!" -- This should never happen. Will be converted to Blocks in the Plushy -> Exec stack process
(Open _) -> error "Error: Open found in exec stack!" -- This should also never happen. Should be converted in Plushy -> Exec stack process
Skip -> error "Error: Skip found in exec stack!" -- This should double also never happen.
CrossoverPadding -> error "Error: CrossoverPadding found in exec stack!"
Gap -> error "Error: Gap found in exec stack!"
interpretExec state = state

10
src/HushGP/PushTests.hs Normal file
View File

@ -0,0 +1,10 @@
module HushGP.PushTests where
-- ( module HushGP.PushTests.GenericTests,
-- module HushGP.PushTests.IntTests,
-- module HushGP.PushTests.UtilTests,
-- )
-- import HushGP.PushTests.GenericTests
-- import HushGP.PushTests.IntTests
-- import HushGP.PushTests.UtilTests

View File

@ -0,0 +1,22 @@
module HushGP.PushTests.GP.Selection where
import Data.List
import HushGP.GP.Individual
import HushGP.State
import HushGP.Utility
-- | One of the steps in the lexicase selection process for selecting initial survivors.
tempFunc0 :: [[Individual]]
tempFunc0 = groupBy (\x y -> fitnessCases x == fitnessCases y) testInds
-- \| Another step forward in the lexicase selection process.
survivors :: IO [Individual]
survivors = mapM randElem tempFunc0
-- | A list of individuals used for testing.
testInds :: [Individual]
testInds =
[ Individual{plushy = [Close], totalFitness = Just 1000, fitnessCases = Just [500,500], selectionCases = Nothing}
, Individual{plushy = [Close], totalFitness = Just 1000, fitnessCases = Just [400,600], selectionCases = Nothing}
, Individual{plushy = [Close], totalFitness = Just 900, fitnessCases = Just [500,400], selectionCases = Nothing}
]

View File

@ -0,0 +1,134 @@
module HushGP.PushTests.GenericTests where
-- import HushGP.State
-- import Control.Lens
-- import Test.Tasty.QuickCheck
-- -- import HushGP.Instructions.GenericInstructions
-- -- The naming scheme:
-- -- the letters at the beginning represent what kind of transformation (the word I'm using for a basic function) to the states is happening
-- -- for example: the function aaa1Test relays this arg takes a transformation of two as and turns them into one a
-- -- the numbers represent how many different stacks are used in the function.
-- -- for example: the aaa1Test relays that it takes one stack as input. These stacks are passed in as Lens
-- -- We may be able to get rid of Lens entirely and use haskell's integrated accessors of type State -> [a]
-- -- You can see what I'm talking about if you go into ghci and type: `:info _int` for example
-- | Test to see if the length difference between the two stacks post execution is off by one.
-- Based on a primitive lens. Should only be used with functions that modify the length of one stack
-- by one. The first Int specifies what size the stacks should differ by. The second Int
-- specifies how many intial items should be in the stack to not be considered a no-op.
-- diff1Test :: (Show a, Eq a) => Lens' State [a] -> (State -> State) -> Int -> State -> Property
-- diff1Test accessor instruction ltAmt state
-- | length (view accessor state) < ltAmt = state === instruction state
-- | otherwise = state =/= instruction state
-- -- aa1Test :: (Show a, Eq a) => Lens' State [a] -> (State -> State) -> (a -> a) -> State -> Property
-- -- aa1Test accessor instruction transformation state =
-- -- case (uncons (view accessor state), uncons (view accessor $ instruction state)) of
-- -- (Just (origx1, _), Just (modx1, _)) -> transformation origx1 === modx1 .&&. length (view accessor state) === length (view accessor $ instruction state)
-- -- _ -> state === instruction state
-- -- | Test to see if the length difference between 2 separate stacks post execution if
-- -- the up/down by a passed amt for the respective stats. Is used to test functions like instructionIntFromFloat.
-- diff2Test :: (Show b, Eq b) => Lens' State [a] -> Lens' State [b] -> (State -> State) -> Int -> State -> Property
-- diff2Test accessorFrom accessorTo instruction ltAmt state
-- | length (view accessorFrom state) < ltAmt = state === instruction state
-- | otherwise = length (view accessorTo $ instruction state) =/= length (view accessorTo state) .&&.
-- length (view accessorFrom $ instruction state) =/= length (view accessorFrom state)
-- case (uncons (view accessorTo $ instruction state), uncons (view accessorFrom state)) of
-- (Just (_, _), Just (_, _)) ->
-- length (view accessorTo $ instruction state) === length (view accessorTo state) + 1 .&&.
-- length (view accessorFrom $ instruction state) === length (view accessorFrom state) - 1
-- _ -> state === instruction state
-- aab2Test :: (Show b, Eq b) => Lens' State [a] -> Lens' State [b] -> (State -> State) -> State -> Property
-- aab2Test accessorFrom accessorTo instruction state =
-- case (uncons (view accessorTo $ instruction state), uncons (view accessorFrom state)) of
-- (Just (_, _), Just (_, _ : _)) ->
-- length (view accessorTo $ instruction state) == length (view accessorTo state) + 1 .&&.
-- length (view accessorFrom $ instruction state) == length (view accessorFrom state) - 2
-- _ -> state === instruction state
-- popTest :: (Show a) => Lens' State [a] -> (State -> State) -> State -> Property
-- popTest accessor instruction state =
-- if null $ view accessor state
-- then state === instruction state
-- else length (view accessor $ instruction state) === length (view accessor state) - 1
-- dupTest :: (Eq a, Show a) => Lens' State [a] -> (State -> State) -> State -> Property
-- dupTest accessor instruction state =
-- case uncons (view accessor state) of
-- Just (origx1, _) ->
-- case uncons (view accessor $ instruction state) of
-- Just (modx1, modx2 : _) ->
-- origx1 === modx1 .&&. origx1 === modx2 .&&. length (view accessor $ instruction state) === length (view accessor state) + 1
-- _ -> state === instruction state
-- _ -> state === instruction state
-- -- How to test the int stack in particular?
-- dupTestN :: (Eq a, Show a) => Lens' State [a] -> (State -> State) -> State -> Property
-- dupTestN accessor instruction state =
-- case uncons (view int state) of
-- Just (i1, is) ->
-- let amt = max i1 0 in
-- case uncons (view accessor state{_int = is}) of
-- Just (origx1, _) ->
-- conjoin (map (origx1 ===) (take amt (view accessor $ instruction state))) .&&.
-- length (view accessor $ instruction state) === (length (view accessor state{_int = is}) + amt - 1)
-- _ -> state === instruction state
-- _ -> state === instruction state
-- swapTest :: (Show a, Eq a) => Lens' State [a] -> (State -> State) -> State -> Property
-- swapTest accessor instruction state =
-- case (uncons (view accessor state), uncons (view accessor $ instruction state)) of
-- (Just (origx1, origx2 : _), Just (modx1, modx2 : _)) -> origx1 === modx2 .&&. origx2 === modx1
-- _ -> state === instruction state
-- rotTest :: (Show a, Eq a) => Lens' State [a] -> (State -> State) -> State -> Property
-- rotTest accessor instruction state =
-- case (uncons (view accessor state), uncons (view accessor $ instruction state)) of
-- (Just (origx1, origx2 : origx3 : _), Just (modx1, modx2 : modx3 : _)) -> (origx1, origx2, origx3) === (modx2, modx3, modx1)
-- _ -> state === instruction state
-- flushTest :: (Show a, Eq a) => Lens' State [a] -> (State -> State) -> State -> Property
-- flushTest accessor instruction state =
-- property $ null $ view accessor $ instruction state
-- stackDepthTest :: (Show a) => Lens' State [a] -> (State -> State) -> State -> Property
-- stackDepthTest accessor instruction state =
-- case uncons (view int $ instruction state) of
-- Just (x1, _) -> x1 === length (view accessor state)
-- _ -> state === instruction state
-- yankTest :: forall a. (Show a, Eq a) => Lens' State [a] -> (State -> State) -> State -> Property
-- yankTest accessor instruction state@(State {_int = i1 : is}) =
-- let
-- myIndex :: Int
-- myIndex = max 0 (min i1 (length (view accessor state{_int = is}) - 1))
-- item :: a
-- item = view accessor state{_int = is} !! myIndex
-- in
-- case (uncons (view accessor $ instruction state), uncons is) of
-- (Just (x1, _), Just (_, _)) -> x1 === item
-- _ -> state === instruction state
-- -- .&&. -- unsure how to get this functional
-- -- length (view accessor state{_int = is}) === length (view accessor $ instruction state)
-- yankTest _ instruction state = state === instruction state
-- -- Might just make this a unit test
-- -- Come back to this later
-- -- yankDupTest :: forall a. (Show a, Eq a) => Lens' State [a] -> (State -> State) -> State -> Property
-- -- yankDupTest accessor instruction state@(State {_int = i1 : is}) =
-- -- let
-- -- myIndex :: Int
-- -- myIndex = max 0 (min i1 (length (view accessor state{_int = is}) - 1))
-- -- item :: a
-- -- item = view accessor state{_int = is} !! myIndex
-- -- in
-- -- case (uncons (view accessor $ instruction state), uncons is) of
-- -- (Just (x1, xs), Just (_, _)) -> x1 === item .&&. (x1 : xs) !! === item
-- -- _ -> state === instruction state
-- -- yankDupTest _ instruction state = state === instruction state
-- -- shoveTest

View File

@ -0,0 +1,33 @@
module HushGP.PushTests.IntTests where
import HushGP.State
import HushGP.Instructions.IntInstructions
import HushGP.PushTests.TestStates
import Control.Lens hiding (uncons)
-- import System.Environment
import Test.Tasty
-- import Test.Tasty.QuickCheck as QC
import Test.Tasty.HUnit
main :: IO ()
main = do
-- setEnv "TASTY_QUICKCHECK_MAX_SIZE" "10"
-- setEnv "TASTY_QUICKCHECK_VERBOSE" "False"
defaultMain intTests
-- |Holds the tree for property and unit tests.
intTests :: TestTree
intTests = testGroup "All Int Tests" [intUnitTests]
intUnitTests :: TestTree
intUnitTests = testGroup "Unit Tests"
[ testCase "Int DupN Success" $ view int (instructionIntDupN exampleState) @?= [5, 5, 5, 8, 9, 6, 10, 11, 15]
, testCase "Int DupN NoOp" $ view int (instructionIntDupN emptyState) @?= []
, testCase "Int Yank Success" $ view int (instructionIntYank exampleState) @?= [6, 5, 8, 9, 10, 11, 15]
, testCase "Int Yank NoOp" $ view int (instructionIntYank emptyState) @?= []
, testCase "Int Shove Success" $ view int (instructionIntShove exampleState) @?= [8, 9, 5, 6, 10, 11, 15]
, testCase "Int Shove NoOp" $ view int (instructionIntShove emptyState) @?= []
, testCase "Int ShoveDup Success" $ view int (instructionIntShoveDup exampleState) @?= [5, 8, 9, 5, 6, 10, 11, 15]
, testCase "Int ShoveDup NoOp" $ view int (instructionIntShoveDup emptyState) @?= []
, testCase "Int DupItems Success" $ view int (instructionIntDupItems exampleState) @?= [5, 8, 9, 5, 8, 9, 6, 10, 11, 15]
]

View File

@ -0,0 +1,24 @@
module HushGP.PushTests.TestStates where
import HushGP.State
import Data.Map qualified as Map
exampleState :: State
exampleState =
State
{ _exec = [],
_code = [],
_int = [3, 5, 8, 9, 6, 10, 11, 15],
_float = [3.23, 9.235, 5.3211, 8.0],
_bool = [True, False],
_string = ["abc", "123"],
_char = ['d', 'e', 'f'],
_parameter = [],
_vectorInt = [[1, 2], [5, 6, 8]],
_vectorFloat = [[1.234, 9.21], [5.42, 6.221, 8.5493]],
_vectorBool = [[True, False], [False, False, True]],
_vectorString = [["this is a sentence", "this is also a sentence"], ["s0", "s1", "s2"]],
_vectorChar = [['z', 'x'], ['r', 'a', 't', 'l']],
_input = Map.empty
}

View File

@ -0,0 +1,36 @@
module HushGP.PushTests.UtilTests where
-- import HushGP.Instructions.Utility
-- import Test.QuickCheck
-- prop_DeleteAtTest :: Int -> [Int] -> Property
-- prop_DeleteAtTest idx lst =
-- idx >= 0 && idx < length lst ==>
-- if null lst
-- then length lst === length (deleteAt idx lst)
-- else length lst === length (deleteAt idx lst) + 1
-- prop_CombineTupleTest :: Int -> ([Int], [Int]) -> Property
-- prop_CombineTupleTest val tup =
-- length (fst tup) + length (snd tup) === length (combineTuple val tup) - 1
-- prop_CombineTupleListTest :: [Int] -> ([Int], [Int]) -> Property
-- prop_CombineTupleListTest lst tup =
-- length (fst tup) + length (snd tup) === length (combineTupleList lst tup) - length lst
-- -- Could use forAll to only generate valid tests
-- prop_InsertAt :: Int -> Int -> [Int] -> Property
-- prop_InsertAt idx val lst =
-- idx >= 0 && idx < length lst ==>
-- length lst === length (insertAt idx val lst) - 1 .&&.
-- insertAt idx val lst !! idx === val
-- prop_ReplaceAt :: Int -> Int -> [Int] -> Property
-- prop_ReplaceAt idx val lst =
-- idx >= 0 && idx < length lst ==>
-- length lst === length (replaceAt idx val lst) .&&.
-- replaceAt idx val lst !! idx === val
-- -- prop_SubList :: Int -> Int -> [Int] -> Property
-- -- prop_SubList idx0 idx1 lst =
-- -- idx

View File

@ -0,0 +1,3 @@
module HushGP.PushTests.VectorIntTests where

244
src/HushGP/State.hs Normal file
View File

@ -0,0 +1,244 @@
{-# LANGUAGE TemplateHaskell, DeriveGeneric #-}
module HushGP.State where
import Control.Lens hiding (elements)
import Data.Map qualified as Map
import System.Random
import GHC.Generics
-- | The exec stack must store heterogenous types,
-- and we must be able to detect that type at runtime.
-- One solution is for the exec stack to be a list of [Gene].
-- The parameter stack could be singular [Gene] or multiple [atomic] types.
data Gene
= GeneInt Integer
| GeneFloat Double
| GeneBool Bool
| GeneString String
| GeneChar Char
| GeneVectorInt [Integer]
| GeneVectorFloat [Double]
| GeneVectorBool [Bool]
| GeneVectorString [String]
| GeneVectorChar [Char]
| -- | State -> State is the function itself. String stores the name of the function.
StateFunc (State -> State, String)
| PlaceInput Int
| Close
| Open Int
| Skip
| Block [Gene]
| GeneIntERC (Integer, StdGen)
| GeneFloatERC (Double, StdGen)
| GeneBoolERC (Bool, StdGen)
| GeneStringERC (String, StdGen)
| GeneCharERC (Char, StdGen)
| GeneVectorIntERC ([Integer], StdGen)
| GeneVectorFloatERC ([Double], StdGen)
| GeneVectorBoolERC ([Bool], StdGen)
| GeneVectorStringERC ([String], StdGen)
| GeneVectorCharERC ([Char], StdGen)
| -- | This is only used in the crossover function in GP/Variation. Should not be in genome besides there.
CrossoverPadding
| -- | This is used in best match crossover (bmx in PushArgs).
Gap
deriving Generic
instance Eq Gene where
GeneInt x == GeneInt y = x == y
GeneFloat x == GeneFloat y = x == y
GeneBool x == GeneBool y = x == y
GeneString x == GeneString y = x == y
GeneChar x == GeneChar y = x == y
PlaceInput x == PlaceInput y = x == y
GeneVectorInt xs == GeneVectorInt ys = xs == ys
GeneVectorFloat xs == GeneVectorFloat ys = xs == ys
GeneVectorBool xs == GeneVectorBool ys = xs == ys
GeneVectorString xs == GeneVectorString ys = xs == ys
GeneVectorChar xs == GeneVectorChar ys = xs == ys
Close == Close = True
Open x == Open y = x == y
Skip == Skip = True
StateFunc (_, nameX) == StateFunc (_, nameY) = nameX == nameY
Block x == Block y = x == y
GeneIntERC (x, _) == GeneIntERC (y, _) = x == y
GeneFloatERC (x, _) == GeneFloatERC (y, _) = x == y
GeneBoolERC (x, _) == GeneBoolERC (y, _) = x == y
GeneStringERC (x, _) == GeneStringERC (y, _) = x == y
GeneCharERC (x, _) == GeneCharERC (y, _) = x == y
GeneVectorIntERC (x, _) == GeneVectorIntERC (y, _) = x == y
GeneVectorFloatERC (x, _) == GeneVectorFloatERC (y, _) = x == y
GeneVectorBoolERC (x, _) == GeneVectorBoolERC (y, _) = x == y
GeneVectorStringERC (x, _) == GeneVectorStringERC (y, _) = x == y
GeneVectorCharERC (x, _) == GeneVectorCharERC (y, _) = x == y
GeneIntERC (x, _) == GeneInt y = x == y
GeneFloatERC (x, _) == GeneFloat y = x == y
GeneBoolERC (x, _) == GeneBool y = x == y
GeneStringERC (x, _) == GeneString y = x == y
GeneCharERC (x, _) == GeneChar y = x == y
GeneVectorIntERC (x, _) == GeneVectorInt y = x == y
GeneVectorFloatERC (x, _) == GeneVectorFloat y = x == y
GeneVectorBoolERC (x, _) == GeneVectorBool y = x == y
GeneVectorStringERC (x, _) == GeneVectorString y = x == y
GeneVectorCharERC (x, _) == GeneVectorChar y = x == y
CrossoverPadding == CrossoverPadding = True
Gap == Gap = True
_ == _ = False
instance Ord Gene where
GeneInt x <= GeneInt y = x <= y
GeneFloat x <= GeneFloat y = x <= y
GeneBool x <= GeneBool y = x <= y
GeneString x <= GeneString y = x <= y
GeneChar x <= GeneChar y = x <= y
PlaceInput x <= PlaceInput y = x <= y
GeneVectorInt xs <= GeneVectorInt ys = xs <= ys
GeneVectorFloat xs <= GeneVectorFloat ys = xs <= ys
GeneVectorBool xs <= GeneVectorBool ys = xs <= ys
GeneVectorString xs <= GeneVectorString ys = xs <= ys
GeneVectorChar xs <= GeneVectorChar ys = xs <= ys
Close <= Close = True
Open x <= Open y = x <= y
Skip <= Skip = True
StateFunc (_, nameX) <= StateFunc (_, nameY) = nameX <= nameY
Block x <= Block y = x <= y
GeneIntERC (x, _) <= GeneIntERC (y, _) = x <= y
GeneFloatERC (x, _) <= GeneFloatERC (y, _) = x <= y
GeneBoolERC (x, _) <= GeneBoolERC (y, _) = x <= y
GeneStringERC (x, _) <= GeneStringERC (y, _) = x <= y
GeneCharERC (x, _) <= GeneCharERC (y, _) = x <= y
GeneVectorIntERC (x, _) <= GeneVectorIntERC (y, _) = x <= y
GeneVectorFloatERC (x, _) <= GeneVectorFloatERC (y, _) = x <= y
GeneVectorBoolERC (x, _) <= GeneVectorBoolERC (y, _) = x <= y
GeneVectorStringERC (x, _) <= GeneVectorStringERC (y, _) = x <= y
GeneVectorCharERC (x, _) <= GeneVectorCharERC (y, _) = x <= y
GeneIntERC (x, _) <= GeneInt y = x <= y
GeneFloatERC (x, _) <= GeneFloat y = x <= y
GeneBoolERC (x, _) <= GeneBool y = x <= y
GeneStringERC (x, _) <= GeneString y = x <= y
GeneCharERC (x, _) <= GeneChar y = x <= y
GeneVectorIntERC (x, _) <= GeneVectorInt y = x <= y
GeneVectorFloatERC (x, _) <= GeneVectorFloat y = x <= y
GeneVectorBoolERC (x, _) <= GeneVectorBool y = x <= y
GeneVectorStringERC (x, _) <= GeneVectorString y = x <= y
GeneVectorCharERC (x, _) <= GeneVectorChar y = x <= y
CrossoverPadding <= CrossoverPadding = True
Gap <= Gap = True
_ <= _ = False
instance Show Gene where
show (GeneInt x) = "Int: " <> show x
show (GeneFloat x) = "Float: " <> show x
show (GeneBool x) = "Bool: " <> show x
show (GeneString x) = "String: " <> x
show (GeneChar x) = "Char: " <> show x
show (StateFunc (_, funcName)) = "Func: " <> funcName
show (PlaceInput x) = "In: " <> show x
show (GeneVectorInt xs) = "Int Vec: " <> show xs
show (GeneVectorFloat xs) = "Float Vec: " <> show xs
show (GeneVectorBool xs) = "Bool Vec: " <> show xs
show (GeneVectorString xs) = "String Vec: " <> show xs
show (GeneVectorChar xs) = "Char Vec: " <> show xs
show Close = "Close"
show (Open x) = "Open: " <> show x
show Skip = "Skip"
show (Block xs) = "Block: " <> show xs
show (GeneIntERC x) = "Int ERC: " <> show x
show (GeneFloatERC x) = "Float ERC: " <> show x
show (GeneBoolERC x) = "Bool ERC: " <> show x
show (GeneStringERC x) = "String ERC: " <> show x
show (GeneCharERC x) = "Char ERC: " <> show x
show (GeneVectorIntERC x) = "Int Vec ERC: " <> show x
show (GeneVectorFloatERC x) = "Float Vec ERC: " <> show x
show (GeneVectorBoolERC x) = "Bool Vec ERC: " <> show x
show (GeneVectorStringERC x) = "String Vec ERC: " <> show x
show (GeneVectorCharERC x) = "Char Vec ERC: " <> show x
show CrossoverPadding = "Crossover Padding"
show Gap = "Gap"
-- instance CoArbitrary StdGen where
-- coarbitrary _ gen = gen
-- instance CoArbitrary Gene
-- instance Arbitrary Gene where
-- arbitrary =
-- oneof
-- [ GeneInt <$> arbitrary,
-- GeneFloat <$> arbitrary,
-- GeneBool <$> arbitrary,
-- GeneString <$> arbitrary,
-- GeneChar <$> arbitrary,
-- StateFunc <$> arbitrary,
-- -- PlaceInput <$> arbitrary,
-- GeneVectorInt <$> arbitrary,
-- GeneVectorFloat <$> arbitrary,
-- GeneVectorBool <$> arbitrary,
-- GeneVectorString <$> arbitrary,
-- GeneVectorChar <$> arbitrary,
-- Block <$> arbitrary
-- ]
-- | The structure that holds all of the values.
data State = State
{ _exec :: [Gene],
_code :: [Gene],
_int :: [Integer],
_float :: [Double],
_bool :: [Bool],
_string :: [String],
_char :: [Char],
_vectorInt :: [[Integer]],
_vectorFloat :: [[Double]],
_vectorBool :: [[Bool]],
_vectorString :: [[String]],
_vectorChar :: [[Char]],
_parameter :: [Gene],
_input :: Map.Map Int Gene
}
deriving (Show, Eq, Ord, Generic)
-- instance CoArbitrary State
-- instance Arbitrary State where
-- arbitrary = do
-- arbExec <- arbitrary
-- arbCode <- arbitrary
-- arbInt <- arbitrary
-- arbFloat <- arbitrary
-- arbBool <- arbitrary
-- arbString <- arbitrary
-- arbChar <- arbitrary
-- arbVectorInt <- arbitrary
-- arbVectorFloat <- arbitrary
-- arbVectorBool <- arbitrary
-- arbVectorString <- arbitrary
-- arbVectorChar <- arbitrary
-- arbParameter <- arbitrary
-- -- arbInput <- arbitrary
-- State arbExec arbCode arbInt arbFloat arbBool arbString arbChar arbVectorInt arbVectorFloat arbVectorBool arbVectorString arbVectorChar arbParameter <$> arbitrary
-- -- Thanks hlint lol
emptyState :: State
emptyState =
State
{ _exec = [],
_code = [],
_int = [],
_float = [],
_bool = [],
_string = [],
_char = [],
_parameter = [],
_vectorInt = [],
_vectorFloat = [],
_vectorBool = [],
_vectorString = [],
_vectorChar = [],
_input = Map.empty
}
-- This must stay at the end of the file.
-- Template haskell seems to be messing with GHC.Generics
$(makeLenses ''State)

38
src/HushGP/TH.hs Normal file
View File

@ -0,0 +1,38 @@
module HushGP.TH where
import Data.List
import Language.Haskell.TH
import Text.Regex.TDFA
-- This old code made this all possible :)
-- https://github.com/finnsson/template-helper/blob/master/src/Language/Haskell/Extract.hs
-- | A way to extract all functions from the file
-- `lines file` pulls all of the lines in one string from the file
-- `lex $ lines file` splits the function into a tuple
-- fst = the function nams, snd = the rest of the line
-- `concatMap lex $ lines file` maps lex onto all of the lines
-- and concats the result into a list
-- `filter (=~pattern) $ map fst $ concatMap lex $ lines file` filters
-- any line that doesn't have the passed pattern to it. "function" is a good pattern
-- for Hush.
-- `nub $ filter (=~pattern) $ map fst $ concatMap lex $ lines file` removes all
-- duplicates from the list. Or sets in this case :)
extractAllFunctions :: String -> Q [String]
extractAllFunctions pattern = do
loc <- location
-- file <- runIO $ readFile pattern
file <- runIO $ readFile $ loc_filename loc
pure $ nub $ filter (=~ pattern) $ map fst $ concatMap lex $ lines file
-- | Extracts all functions from a Q [String] (to be used with extractAllFunctions)
-- funcs has a list of all functions from extractAllFunctions
-- makePair makes a tuple of a passed function holding its name as a string and actual function value
-- in that order. StateFunc :)
-- `ListE $ map makePair funcs` makes a list of these function tuples holding all function
-- names and values.
functionExtractor :: String -> Q Exp
functionExtractor pattern = do
funcs <- extractAllFunctions pattern
let makePair n = TupE [Just $ VarE $ mkName n, Just $ LitE $ StringL n]
pure $ ListE $ map makePair funcs

View File

@ -0,0 +1,19 @@
module HushGP.Tools.Metrics where
import Data.List
import System.Random
-- |Maps minimum over the transposed [[Double]].
minOfColumns :: (Num a, Ord a) => [[a]] -> [a]
minOfColumns columns = map minimum (transpose columns)
-- |Returns the index of the maximum value in a list, randomly tiebreaking.
argMax :: Ord a => [a] -> IO Int
argMax xs = argMaxHead . fst . uniformShuffleList (elemIndices (maximum xs) xs) <$> initStdGen
-- |Takes the first element from a list and returns an error as specified. For use with
-- the argMax function.
argMaxHead :: [a] -> a
argMaxHead xs = case uncons xs of
Just (x, _) -> x
_ -> error "Error: Head is empty in argMax!"

50
src/HushGP/Utility.hs Normal file
View File

@ -0,0 +1,50 @@
module HushGP.Utility where
import Control.Monad
import Data.List
import HushGP.State
import System.Random
-- | Generates a single random instruction from a list of instructions.
randomInstruction :: [Gene] -> IO Gene
randomInstruction instructions = do
impureGen <- initStdGen
pure $ instructions !! fst (uniformR (0, length instructions - 1) impureGen)
-- | Generates a list of random instructions from a list of instructions passed in.
randomInstructions :: Int -> [Gene] -> IO [Gene]
randomInstructions amt instructions = replicateM amt (randomInstruction instructions)
-- | Maps a function like the normal mapping function and also applies an index to it.
mapIndexed :: (Int -> a -> b) -> [a] -> [b]
mapIndexed = mapIndexed' 0
-- | Internals for mapIndexed, can supply a starting index for rather than just 0
-- with mapIndexed.
mapIndexed' :: Int -> (Int -> a -> b) -> [a] -> [b]
mapIndexed' _ _ [] = []
mapIndexed' count f (x : xs) = f count x : mapIndexed' (count + 1) f xs
-- | Returns a random element from a passed list. No generator required.
randElem :: [a] -> IO a
randElem xs = (xs !!) . fst . uniformR (0, length xs - 1) <$> initStdGen
-- | Used in some of the selection operations. Returns an error saying cases is empty.
headCases :: [Int] -> Int
headCases xs = case uncons xs of Just (y, _) -> y; _ -> error "Error: cases is empty!"
-- | Almost a constant but has some randomness inside. Double for more decimal precision.
-- Noise of mean of 0 and std dev of 1. This is a neat function to visualize on desmos!
gaussianNoiseFactor :: IO Double
gaussianNoiseFactor = do
randDecimal0 <- fst . uniformR (0.0 :: Double, 1.0 :: Double) <$> initStdGen
randDecimal1 <- fst . uniformR (0.0 :: Double, 1.0 :: Double) <$> initStdGen
pure (sqrt ((-2.0) * log randDecimal0) * cos (2.0 * pi * randDecimal1))
-- | A random Int between 1 and 100 inclusive.
randOneToOneHundred :: IO Int
randOneToOneHundred = fst . uniformR (1 :: Int, 100 :: Int) <$> initStdGen
-- | A random Double between 0.1 and 1.0 inclusive.
randZeroToOne :: IO Double
randZeroToOne = fst . uniformR (0.1 :: Double, 1.0 :: Double) <$> initStdGen

View File

@ -1,30 +0,0 @@
module Instructions (
module Instructions.GenericInstructions,
module Instructions.IntInstructions,
module Instructions.FloatInstructions,
module Instructions.StringInstructions,
module Instructions.CharInstructions,
module Instructions.CodeInstructions,
module Instructions.ExecInstructions,
module Instructions.LogicalInstructions,
module Instructions.VectorIntInstructions,
module Instructions.VectorFloatInstructions,
module Instructions.VectorStringInstructions,
module Instructions.VectorLogicalInstructions,
module Instructions.VectorCharInstructions
)
where
import Instructions.GenericInstructions
import Instructions.IntInstructions
import Instructions.FloatInstructions
import Instructions.StringInstructions
import Instructions.CharInstructions
import Instructions.CodeInstructions
import Instructions.ExecInstructions
import Instructions.LogicalInstructions
import Instructions.VectorIntInstructions
import Instructions.VectorFloatInstructions
import Instructions.VectorStringInstructions
import Instructions.VectorLogicalInstructions
import Instructions.VectorCharInstructions

View File

@ -1,89 +0,0 @@
module Instructions.CharInstructions where
import Data.Char
import State
import Instructions.StringInstructions (wschars)
import Instructions.GenericInstructions
intToAscii :: Integral a => a -> Char
intToAscii val = chr (abs (fromIntegral val) `mod` 128)
instructionCharConcat :: State -> State
instructionCharConcat state@(State {_char = c1 : c2 : cs, _string = ss}) = state{_char = cs, _string = [c1, c2] : ss}
instructionCharConcat state = state
instructionCharFromFirstChar :: State -> State
instructionCharFromFirstChar state = instructionVectorFirst state char string
instructionCharFromLastChar :: State -> State
instructionCharFromLastChar state = instructionVectorLast state char string
instructionCharFromNthChar :: State -> State
instructionCharFromNthChar state = instructionVectorNth state char string
instructionCharIsWhitespace :: State -> State
instructionCharIsWhitespace state@(State {_char = c1 : cs, _bool = bs}) = state{_char = cs, _bool = (c1 `elem` wschars) : bs}
instructionCharIsWhitespace state = state
instructionCharIsLetter :: State -> State
instructionCharIsLetter state@(State {_char = c1 : cs, _bool = bs}) = state{_char = cs, _bool = isAlpha c1 : bs}
instructionCharIsLetter state = state
instructionCharIsDigit :: State -> State
instructionCharIsDigit state@(State {_char = c1 : cs, _bool = bs}) = state{_char = cs, _bool = isDigit c1 : bs}
instructionCharIsDigit state = state
instructionCharFromBool :: State -> State
instructionCharFromBool state@(State {_char = cs, _bool = b1 : bs}) = state{_char = (if b1 then 'T' else 'F') : cs, _bool = bs}
instructionCharFromBool state = state
instructionCharFromAsciiInt :: State -> State
instructionCharFromAsciiInt state@(State {_char = cs, _int = i1 : is}) = state{_char = intToAscii i1 : cs, _int = is}
instructionCharFromAsciiInt state = state
instructionCharFromAsciiFloat :: State -> State
instructionCharFromAsciiFloat state@(State {_char = cs, _float = f1 : fs}) = state{_char = intToAscii @Integer (floor f1) : cs, _float = fs}
instructionCharFromAsciiFloat state = state
instructionCharsFromString :: State -> State
instructionCharsFromString state@(State {_char = cs, _string = s1 : ss}) = state{_char = s1 <> cs, _string = ss}
instructionCharsFromString state = state
instructionCharPop :: State -> State
instructionCharPop state = instructionPop state char
instructionCharDup :: State -> State
instructionCharDup state = instructionDup state char
instructionCharDupN :: State -> State
instructionCharDupN state = instructionDupN state char
instructionCharSwap :: State -> State
instructionCharSwap state = instructionSwap state char
instructionCharRot :: State -> State
instructionCharRot state = instructionRot state char
instructionCharFlush :: State -> State
instructionCharFlush state = instructionFlush state char
instructionCharEq :: State -> State
instructionCharEq state = instructionEq state char
instructionCharStackDepth :: State -> State
instructionCharStackDepth state = instructionStackDepth state char
instructionCharYank :: State -> State
instructionCharYank state = instructionYank state char
instructionCharYankDup :: State -> State
instructionCharYankDup state = instructionYankDup state char
instructionCharIsEmpty :: State -> State
instructionCharIsEmpty state = instructionIsEmpty state char
instructionCharShove :: State -> State
instructionCharShove state = instructionShove state char
instructionCharShoveDup :: State -> State
instructionCharShoveDup state = instructionShoveDup state char

View File

@ -1,310 +0,0 @@
module Instructions.CodeInstructions where
import Data.List (elemIndex)
import State
import Instructions.GenericInstructions
import Instructions.IntInstructions
-- import Debug.Trace
isBlock :: Gene -> Bool
isBlock (Block _) = True
isBlock _ = False
blockLength :: Gene -> Int
blockLength (Block xs) = length xs
blockLength _ = 1
blockIsNull :: Gene -> Bool
blockIsNull (Block xs) = null xs
blockIsNull _ = False
-- I think I can abstract the boilerplate base case check for a lot of these
-- with a different function
-- empty Blocks are a thing but that shouldn't really matter
extractFirstFromBlock :: Gene -> Gene
extractFirstFromBlock (Block (x : _)) = x
extractFirstFromBlock gene = gene
extractLastFromBlock :: Gene -> Gene
extractLastFromBlock (Block []) = Block []
extractLastFromBlock (Block xs) = last xs
extractLastFromBlock gene = gene
extractInitFromBlock :: Gene -> Gene
extractInitFromBlock (Block []) = Block []
extractInitFromBlock (Block xs) = Block (init xs)
extractInitFromBlock gene = gene
extractTailFromBlock :: Gene -> Gene
extractTailFromBlock (Block xs) = Block (drop 1 xs)
extractTailFromBlock gene = gene
-- This function took at least 3 hours to program.
codeAtPoint :: [Gene] -> Int -> Gene
codeAtPoint (gene : _) 0 = gene
codeAtPoint [] _ = Block [] -- Should only happen if an empty block is last Gene in the list of Genes
codeAtPoint ((Block nestedGenes) : genes) index = codeAtPoint (nestedGenes <> genes) (index - 1)
codeAtPoint (_ : genes) index = codeAtPoint genes (index - 1)
codeInsertAtPoint :: [Gene] -> Gene -> Int -> [Gene]
codeInsertAtPoint oldGenes gene 0 = gene : oldGenes
codeInsertAtPoint [] gene _ = [gene] -- This shouldn't happen (lol)
codeInsertAtPoint ((Block genes) : oldGenes) gene index = Block (codeInsertAtPoint genes gene (index - 1)) : oldGenes
codeInsertAtPoint (oldGene : oldGenes) gene index = oldGene : codeInsertAtPoint oldGenes gene (index - 1)
-- This one functions differently than pysh.
-- I like this one because it preserves ordering in the second case
codeCombine :: Gene -> Gene -> Gene
codeCombine (Block xs) (Block ys) = Block (xs <> ys)
codeCombine (Block xs) ygene = Block (xs <> [ygene])
codeCombine xgene (Block ys) = Block (xgene : ys)
codeCombine xgene ygene = Block [xgene, ygene]
codeMember :: Gene -> Gene -> Bool
codeMember (Block _) (Block _) = False -- Can't compare two lists with `elem`
codeMember (Block xs) ygene = ygene `elem` xs
codeMember _ _ = False
-- I love list comprehensions
codeRecursiveSize :: Gene -> Int
codeRecursiveSize (Block xs) = sum [codeRecursiveSize x + if isBlock x then 1 else 0 | x <- xs]
codeRecursiveSize _ = 1
instructionCodePop :: State -> State
instructionCodePop state = instructionPop state code
instructionCodeIsCodeBlock :: State -> State
instructionCodeIsCodeBlock state@(State {_code = (c : cs), _bool = bs}) = state {_code = cs, _bool = isBlock c : bs}
instructionCodeIsCodeBlock state = state
instructionCodeIsSingular :: State -> State
instructionCodeIsSingular state@(State {_code = (c : cs), _bool = bs}) = state {_code = cs, _bool = not (isBlock c) : bs}
instructionCodeIsSingular state = state
instructionCodeLength :: State -> State
instructionCodeLength state@(State {_code = (c : cs), _int = is}) = state {_code = cs, _int = blockLength c : is}
instructionCodeLength state = state
instructionCodeFirst :: State -> State
instructionCodeFirst state@(State {_code = (c : cs)}) = state {_code = extractFirstFromBlock c : cs}
instructionCodeFirst state = state
instructionCodeLast :: State -> State
instructionCodeLast state@(State {_code = (c : cs)}) = state {_code = extractLastFromBlock c : cs}
instructionCodeLast state = state
-- https://erp12.github.io/pyshgp/html/core_instructions.html#code-rest
instructionCodeTail :: State -> State
instructionCodeTail state@(State {_code = (c : cs)}) = state {_code = extractTailFromBlock c : cs}
instructionCodeTail state = state
-- https://erp12.github.io/pyshgp/html/core_instructions.html#code-but-last
instructionCodeInit :: State -> State
instructionCodeInit state@(State {_code = (c : cs)}) = state {_code = extractInitFromBlock c : cs}
instructionCodeInit state = state
instructionCodeWrap :: State -> State
instructionCodeWrap state@(State {_code = (c : cs)}) = state {_code = Block [c] : cs}
instructionCodeWrap state = state
instructionCodeList :: State -> State
instructionCodeList state@(State {_code = (c1 : c2 : cs)}) = state {_code = Block [c1, c2] : cs}
instructionCodeList state = state
instructionCodeCombine :: State -> State
instructionCodeCombine state@(State {_code = (c1 : c2 : cs)}) = state {_code = codeCombine c1 c2 : cs}
instructionCodeCombine state = state
instructionCodeDo :: State -> State
instructionCodeDo state@(State {_code = (c1 : cs), _exec = es}) = state {_code = cs, _exec = c1: es}
instructionCodeDo state = state
instructionCodeDoDup :: State -> State
instructionCodeDoDup state@(State {_code = (c1 : cs), _exec = es}) = state {_code = c1 : cs, _exec = c1 : es}
instructionCodeDoDup state = state
-- https://erp12.github.io/pyshgp/html/core_instructions.html#code-do-then-pop
instructionCodeDoThenPop :: State -> State
instructionCodeDoThenPop state@(State {_code = c1 : _, _exec = es}) = state {_exec = c1 : StateFunc instructionCodePop : es}
instructionCodeDoThenPop state = state
instructionCodeDoRange :: State -> State
instructionCodeDoRange state@(State {_code = (c1 : cs), _int = (i0 : i1 : is), _exec = es}) =
if increment i0 i1 /= 0
then state {_exec = c1 : Block [GeneInt (i1 + increment i0 i1), GeneInt i0, StateFunc instructionCodeFromExec, c1, StateFunc instructionCodeDoRange] : es, _int = i1 : is, _code = cs}
else state {_exec = c1: es, _int = i1 : is, _code = cs}
where
increment :: Int -> Int -> Int
increment destIdx currentIdx
| currentIdx < destIdx = 1
| currentIdx > destIdx = -1
| otherwise = 0
instructionCodeDoRange state = state
instructionCodeDoCount :: State -> State
instructionCodeDoCount state@(State {_code = (c : cs), _int = (i : is), _exec = es}) =
if i < 1
then state
else state {_code = cs, _int = is, _exec = Block [GeneInt 0, GeneInt $ i - 1, StateFunc instructionCodeFromExec, c, StateFunc instructionCodeDoRange] : es}
instructionCodeDoCount state = state
instructionCodeDoTimes :: State -> State
instructionCodeDoTimes state@(State {_code = (c : cs), _int = (i : is), _exec = es}) =
if i < 1
then state
else state {_code = cs, _int = is, _exec = Block [GeneInt 0, GeneInt $ i - 1, StateFunc instructionCodeFromExec, Block [StateFunc instructionIntPop, c], StateFunc instructionCodeDoRange] : es}
instructionCodeDoTimes state = state
instructionCodeIf :: State -> State
instructionCodeIf state@(State {_code = (c1 : c2 : cs), _bool = (b1 : bs), _exec = es}) = state{_code = cs, _bool = bs, _exec = (if b1 then c1 else c2) : es}
instructionCodeIf state = state
instructionCodeWhen :: State -> State
instructionCodeWhen state@(State {_code = (c1 : cs), _bool = (b1 : bs), _exec = es}) = state{_code = cs, _bool = bs, _exec = if b1 then c1 : es else es}
instructionCodeWhen state = state
instructionCodeMember :: State -> State
instructionCodeMember state@(State {_code = (c1 : c2 : cs), _bool = bs}) = state{_code = cs, _bool = codeMember c1 c2 : bs}
instructionCodeMember state = state
-- This one doesn't count the recursive Blocks while instructionCodeExtract does
-- https://erp12.github.io/pyshgp/html/core_instructions.html#code-nth
instructionCodeN :: State -> State
instructionCodeN state@(State {_code = ((Block c1) : cs), _int = (i1 : is)}) =
if not $ null c1
then state {_code = c1 !! index : cs, _int = is}
else state
where
index :: Int
index = abs i1 `mod` length c1
instructionCodeN state@(State {_code = (c1 : cs), _int = _ : is}) = state {_code = c1 : cs, _int = is}
instructionCodeN state = state
instructionMakeEmptyCodeBlock :: State -> State
instructionMakeEmptyCodeBlock state@(State {_code = cs}) = state {_code = Block [] : cs}
instructionIsEmptyCodeBlock :: State -> State
instructionIsEmptyCodeBlock state@(State {_code = Block c1 : cs, _bool = bs}) = state{_code = cs, _bool = null c1 : bs}
instructionIsEmptyCodeBlock state@(State {_bool = bs}) = state{_bool = False : bs}
instructionCodeSize :: State -> State
instructionCodeSize state@(State {_code = c1 : cs, _int = is}) = state{_code = cs, _int = codeRecursiveSize c1 : is}
instructionCodeSize state = state
-- There's a bug for this instruction in pysh where the last item in the
-- top level Block isn't counted, and if passed 0, then the entire codeblock is returned.
-- I designed this function differently so 0 returns the 0th element, and the last item
-- in the codeblock can be returned.
instructionCodeExtract :: State -> State
instructionCodeExtract state@(State {_code = (block@(Block c1) : cs), _int = i1 : is}) =
let
index = abs i1 `mod` codeRecursiveSize block
in
state{_code = codeAtPoint c1 index : cs, _int = is}
instructionCodeExtract state@(State {_code = cs, _int = _ : is}) = state{_code = cs, _int = is}
instructionCodeExtract state = state
instructionCodeInsert :: State -> State
instructionCodeInsert state@(State {_code = (block@(Block c1) : c2 : cs), _int = i1 : is}) =
let
index = abs i1 `mod` codeRecursiveSize block
in
state{_code = Block (codeInsertAtPoint c1 c2 index) : cs, _int = is}
instructionCodeInsert state@(State {_code = c1 : c2 : cs, _int = i1 : is}) =
let
index = abs i1 `mod` codeRecursiveSize (Block [c1])
in
state{_code = Block (codeInsertAtPoint [c1] c2 index) : cs, _int = is}
instructionCodeInsert state = state
-- How do I test if two functions are the same??????????
-- This will impact the final case. This implementation can't determine
-- if two functions are the same, so it assumes that they are.
-- Maybe can test for equality by seeing if these two functions affect the current state
-- in the same way.
instructionCodeFirstPosition :: State -> State
instructionCodeFirstPosition state@(State {_code = (Block []) : c2 : cs, _int = is}) = state {_code = cs, _int = (if c2 == Block [] then 0 else -1) : is}
instructionCodeFirstPosition state@(State {_code = (Block c1) : c2 : cs, _int = is}) = state {_code = cs, _int = positionElem c1 c2 : is}
where
-- This is really not gonna be good for StateFunc
positionElem :: [Gene] -> Gene -> Int
positionElem genes gene =
case elemIndex gene genes of
Nothing -> -1
Just x -> x
instructionCodeFirstPosition state@(State {_code = c1 : c2 : cs, _int = is}) = state {_code = cs, _int = (if c1 == c2 then 0 else -1) : is}
instructionCodeFirstPosition state = state
instructionCodeReverse :: State -> State
instructionCodeReverse state@(State {_code = (Block c1) : cs}) = state {_code = Block (reverse c1) : cs}
instructionCodeReverse state = state
instructionCodeDup :: State -> State
instructionCodeDup state = instructionDup state code
instructionCodeDupN :: State -> State
instructionCodeDupN state = instructionDupN state code
instructionCodeSwap :: State -> State
instructionCodeSwap state = instructionSwap state code
instructionCodeRot :: State -> State
instructionCodeRot state = instructionRot state code
instructionCodeFlush :: State -> State
instructionCodeFlush state = instructionFlush state code
instructionCodeEq :: State -> State
instructionCodeEq state = instructionEq state code
instructionCodeStackDepth :: State -> State
instructionCodeStackDepth state = instructionStackDepth state code
instructionCodeYank :: State -> State
instructionCodeYank state = instructionYank state code
instructionCodeYankDup :: State -> State
instructionCodeYankDup state = instructionYankDup state code
instructionCodeStackIsEmpty :: State -> State
instructionCodeStackIsEmpty state = instructionIsEmpty state code
instructionCodeShove :: State -> State
instructionCodeShove state = instructionShove state code
instructionCodeShoveDup :: State -> State
instructionCodeShoveDup state = instructionShoveDup state code
instructionCodeFromBool :: State -> State
instructionCodeFromBool state = instructionCodeFrom state bool GeneBool
instructionCodeFromInt :: State -> State
instructionCodeFromInt state = instructionCodeFrom state int GeneInt
instructionCodeFromChar :: State -> State
instructionCodeFromChar state = instructionCodeFrom state char GeneChar
instructionCodeFromFloat :: State -> State
instructionCodeFromFloat state = instructionCodeFrom state float GeneFloat
instructionCodeFromString :: State -> State
instructionCodeFromString state = instructionCodeFrom state string GeneString
instructionCodeFromVectorInt :: State -> State
instructionCodeFromVectorInt state = instructionCodeFrom state vectorInt GeneVectorInt
instructionCodeFromVectorFloat :: State -> State
instructionCodeFromVectorFloat state = instructionCodeFrom state vectorFloat GeneVectorFloat
instructionCodeFromVectorString :: State -> State
instructionCodeFromVectorString state = instructionCodeFrom state vectorString GeneVectorString
instructionCodeFromVectorBool :: State -> State
instructionCodeFromVectorBool state = instructionCodeFrom state vectorBool GeneVectorBool
instructionCodeFromVectorChar :: State -> State
instructionCodeFromVectorChar state = instructionCodeFrom state vectorChar GeneVectorChar
instructionCodeFromExec :: State -> State
instructionCodeFromExec state = instructionCodeFrom state exec id

View File

@ -1,100 +0,0 @@
module Instructions.ExecInstructions where
import State
import Instructions.IntInstructions
import Instructions.GenericInstructions
instructionExecIf :: State -> State
instructionExecIf state@(State {_exec = (e1 : e2 : es), _bool = (b : bs)}) =
if b
then state {_exec = e1 : es, _bool = bs}
else state {_exec = e2 : es, _bool = bs}
instructionExecIf state = state
instructionExecDup :: State -> State
instructionExecDup state = instructionDup state exec
instructionExecDupN :: State -> State
instructionExecDupN state = instructionDupN state exec
instructionExecPop :: State -> State
instructionExecPop state = instructionPop state exec
instructionExecSwap :: State -> State
instructionExecSwap state = instructionSwap state exec
instructionExecRot :: State -> State
instructionExecRot state = instructionRot state exec
instructionExecFlush :: State -> State
instructionExecFlush state = instructionFlush state exec
instructionExecEq :: State -> State
instructionExecEq state = instructionEq state exec
instructionExecStackDepth :: State -> State
instructionExecStackDepth state = instructionStackDepth state exec
instructionExecYank :: State -> State
instructionExecYank state = instructionYank state exec
instructionExecYankDup :: State -> State
instructionExecYankDup state = instructionYankDup state exec
instructionExecShove :: State -> State
instructionExecShove state = instructionShove state exec
instructionExecShoveDup :: State -> State
instructionExecShoveDup state = instructionShoveDup state exec
instructionExecIsEmpty :: State -> State
instructionExecIsEmpty state = instructionIsEmpty state exec
instructionExecDoRange :: State -> State
instructionExecDoRange state@(State {_exec = (e1 : es), _int = (i0 : i1 : is)}) =
if increment i0 i1 /= 0
then state {_exec = e1 : Block [GeneInt (i1 + increment i0 i1), GeneInt i0, StateFunc instructionExecDoRange, e1] : es, _int = i1 : is}
else state {_exec = e1 : es, _int = i1 : is}
where
increment :: Int -> Int -> Int
increment destIdx currentIdx
| currentIdx < destIdx = 1
| currentIdx > destIdx = -1
| otherwise = 0
instructionExecDoRange state = state
instructionExecDoCount :: State -> State
instructionExecDoCount state@(State {_exec = (e : es), _int = (i : is)}) =
if i < 1
then state
else state {_exec = Block [GeneInt 0, GeneInt $ i - 1, StateFunc instructionExecDoRange, e] : es, _int = is}
instructionExecDoCount state = state
instructionExecDoTimes :: State -> State
instructionExecDoTimes state@(State {_exec = (e : es), _int = (i : is)}) =
if i < 1
then state
else state {_exec = Block [GeneInt 0, GeneInt $ i - 1, StateFunc instructionExecDoRange, Block [StateFunc instructionIntPop, e]] : es, _int = is}
instructionExecDoTimes state = state
instructionExecWhile :: State -> State
instructionExecWhile state@(State {_exec = (_ : es), _bool = []}) =
state {_exec = es}
instructionExecWhile state@(State {_exec = alles@(e : es), _bool = (b : bs)}) =
if b
then state {_exec = e : StateFunc instructionExecWhile : alles, _bool = bs}
else state {_exec = es}
instructionExecWhile state = state
instructionExecDoWhile :: State -> State
instructionExecDoWhile state@(State {_exec = alles@(e : _)}) =
state {_exec = e : StateFunc instructionExecWhile : alles}
instructionExecDoWhile state = state
-- Eats the _boolean no matter what
instructionExecWhen :: State -> State
instructionExecWhen state@(State {_exec = (_ : es), _bool = (b : bs)}) =
if not b
then state {_exec = es, _bool = bs}
else state {_bool = bs}
instructionExecWhen state = state

View File

@ -1,116 +0,0 @@
module Instructions.FloatInstructions where
import Data.Fixed (mod')
import Instructions.GenericInstructions
import State
instructionFloatFromInt :: State -> State
instructionFloatFromInt state@(State {_float = fs, _int = (i : is)}) = state {_float = (fromIntegral i :: Float) : fs, _int = is}
instructionFloatFromInt state = state
instructionFloatFromBool :: State -> State
instructionFloatFromBool state@(State {_bool = (b : bs), _float = fs}) = state {_bool = bs, _float = (if b then 1.0 else 0.0) : fs}
instructionFloatFromBool state = state
instructionFloatAdd :: State -> State
instructionFloatAdd state@(State {_float = (f1 : f2 : fs)}) = state {_float = f2 + f1 : fs}
instructionFloatAdd state = state
instructionFloatSub :: State -> State
instructionFloatSub state@(State {_float = (f1 : f2 : fs)}) = state {_float = f2 - f1 : fs}
instructionFloatSub state = state
instructionFloatMul :: State -> State
instructionFloatMul state@(State {_float = (f1 : f2 : fs)}) = state {_float = f2 * f1 : fs}
instructionFloatMul state = state
instructionFloatDiv :: State -> State
instructionFloatDiv state@(State {_float = (f1 : f2 : fs)}) = state {_float = if f1 /= 0 then f2 / f1 : fs else f1 : f2 : fs}
instructionFloatDiv state = state
instructionFloatMod :: State -> State
instructionFloatMod state@(State {_float = (f1 : f2 : fs)}) = state {_float = f2 `mod'` f1 : fs}
instructionFloatMod state = state
instructionFloatMin :: State -> State
instructionFloatMin state@(State {_float = (f1 : f2 : fs)}) = state {_float = min f1 f2 : fs}
instructionFloatMin state = state
instructionFloatMax :: State -> State
instructionFloatMax state@(State {_float = (f1 : f2 : fs)}) = state {_float = max f1 f2 : fs}
instructionFloatMax state = state
instructionFloatInc :: State -> State
instructionFloatInc state@(State {_float = (f1 : fs)}) = state {_float = f1 + 1 : fs}
instructionFloatInc state = state
instructionFloatDec :: State -> State
instructionFloatDec state@(State {_float = (f1 : fs)}) = state {_float = f1 - 1 : fs}
instructionFloatDec state = state
instructionFloatLT :: State -> State
instructionFloatLT state@(State {_float = f1 : f2 : fs, _bool = bs}) = state {_float = fs, _bool = (f1 < f2) : bs}
instructionFloatLT state = state
instructionFloatGT :: State -> State
instructionFloatGT state@(State {_float = f1 : f2 : fs, _bool = bs}) = state {_float = fs, _bool = (f1 > f2) : bs}
instructionFloatGT state = state
instructionFloatLTE :: State -> State
instructionFloatLTE state@(State {_float = f1 : f2 : fs, _bool = bs}) = state {_float = fs, _bool = (f1 <= f2) : bs}
instructionFloatLTE state = state
instructionFloatGTE :: State -> State
instructionFloatGTE state@(State {_float = f1 : f2 : fs, _bool = bs}) = state {_float = fs, _bool = (f1 >= f2) : bs}
instructionFloatGTE state = state
instructionFloatPop :: State -> State
instructionFloatPop state = instructionPop state float
instructionFloatDup :: State -> State
instructionFloatDup state = instructionDup state float
instructionFloatDupN :: State -> State
instructionFloatDupN state = instructionDupN state float
instructionFloatSwap :: State -> State
instructionFloatSwap state = instructionSwap state float
instructionFloatRot :: State -> State
instructionFloatRot state = instructionRot state float
instructionFloatFlush :: State -> State
instructionFloatFlush state = instructionFlush state float
instructionFloatEq :: State -> State
instructionFloatEq state = instructionEq state float
instructionFloatStackDepth :: State -> State
instructionFloatStackDepth state = instructionStackDepth state float
instructionFloatYankDup :: State -> State
instructionFloatYankDup state = instructionYankDup state float
instructionFloatYank :: State -> State
instructionFloatYank state = instructionYank state float
instructionFloatShoveDup :: State -> State
instructionFloatShoveDup state = instructionShoveDup state float
instructionFloatShove :: State -> State
instructionFloatShove state = instructionShove state float
instructionFloatIsEmpty :: State -> State
instructionFloatIsEmpty state = instructionIsEmpty state float
instructionFloatSin :: State -> State
instructionFloatSin state@(State {_float = f1 : fs}) = state {_float = sin f1 : fs}
instructionFloatSin state = state
instructionFloatCos :: State -> State
instructionFloatCos state@(State {_float = f1 : fs}) = state {_float = cos f1 : fs}
instructionFloatCos state = state
instructionFloatTan :: State -> State
instructionFloatTan state@(State {_float = f1 : fs}) = state {_float = tan f1 : fs}
instructionFloatTan state = state

View File

@ -1,347 +0,0 @@
module Instructions.GenericInstructions where
import Control.Lens
import State
-- import Debug.Trace
deleteAt :: Int -> [a] -> [a]
deleteAt idx xs = take idx xs <> drop 1 (drop idx xs)
combineTuple :: a -> ([a], [a]) -> [a]
combineTuple val tup = fst tup <> [val] <> snd tup
combineTupleList :: [a] -> ([a], [a]) -> [a]
combineTupleList val tup = fst tup <> val <> snd tup
insertAt :: Int -> a -> [a] -> [a]
insertAt idx val xs = combineTuple val (splitAt idx xs)
replaceAt :: Int -> a -> [a] -> [a]
replaceAt idx val xs = deleteAt (idx + 1) (insertAt idx val xs)
subList :: Int -> Int -> [a] -> [a]
subList idx0 idx1 xs =
let
(start, end) = if idx0 <= idx1 then (idx0, idx1) else (idx1, idx0)
adjStart = max 0 start
adjEnd = min end (length xs)
in
take adjEnd (drop adjStart xs)
-- Maybe could've used Data.List.isSubsequenceOf :shrug:
findSubA :: forall a. Eq a => [a] -> [a] -> Int
findSubA fullA subA
| length fullA < length subA = -1
| length fullA == length subA = if fullA == subA then 0 else -1
| otherwise = findSubA' fullA subA 0
where
findSubA' :: [a] -> [a] -> Int -> Int
findSubA' fA sA subIndex
| null fA = -1
| length sA > length fA = -1
| sA == take (length sA) fA = subIndex
| otherwise = findSubA' (drop 1 fA) sA (subIndex + 1)
-- The int is the amount of olds to replace with new
-- Just chain findSubA calls lol
-- Nothing means replace all
-- May not be the most efficient method with the findSubA calls
replace :: Eq a => [a] -> [a] -> [a] -> Maybe Int -> [a]
replace fullA old new (Just amt) =
if findSubA fullA old /= -1 && amt > 0
then replace (take (findSubA fullA old) fullA <> new <> drop (findSubA fullA old + length old) fullA) old new (Just $ amt - 1)
else fullA
replace fullA old new Nothing =
if findSubA fullA old /= -1
then replace (take (findSubA fullA old) fullA <> new <> drop (findSubA fullA old + length old) fullA) old new Nothing
else fullA
-- a rather inefficient search
amtOccurences :: forall a. Eq a => [a] -> [a] -> Int
amtOccurences fullA subA = amtOccurences' fullA subA 0
where
amtOccurences' :: [a] -> [a] -> Int -> Int
amtOccurences' fA sA count =
if findSubA fA sA /= -1
then amtOccurences' (replace fA sA mempty (Just 1)) sA (count + 1)
else count
takeR :: Int -> [a] -> [a]
takeR amt fullA = drop (length fullA - amt) fullA
dropR :: Int -> [a] -> [a]
dropR amt fullA = take (length fullA - amt) fullA
safeInit :: [a] -> [a]
safeInit [] = []
safeInit xs = init xs
absNum :: Integral a => a -> [b] -> Int
absNum rawNum lst = abs (fromIntegral rawNum) `mod` length lst
notEmptyStack :: State -> Lens' State [a] -> Bool
notEmptyStack state accessor = not . null $ view accessor state
instructionDup :: State -> Lens' State [a] -> State
instructionDup state accessor =
case uncons (view accessor state) of
Nothing -> state
Just (x,_) -> state & accessor .~ x : view accessor state
instructionPop :: State -> Lens' State [a] -> State
instructionPop state accessor = state & accessor .~ drop 1 (view accessor state)
instructionIsEmpty :: State -> Lens' State [a] -> State
instructionIsEmpty state@(State {_bool = bs}) accessor = state{_bool = null (view accessor state) : bs}
-- instructionPop :: State -> Lens' State [a] -> State
-- instructionPop state accessor = if notEmptyStack state accessor then instructionPop state accessor else state
-- I might be able to move some of the int stack error checking
-- to the integer call. For now this may be a tad inefficient.
instructionDupN :: forall a. State -> Lens' State [a] -> State
instructionDupN state accessor =
case uncons (view int state) of
Just (i1,is) ->
case uncons (view accessor state{_int = is}) of
Just (a1,as) -> instructionDupNHelper i1 a1 accessor (state{_int = is} & accessor .~ as)
_ -> state
_ -> state
where
instructionDupNHelper :: Int -> a -> Lens' State [a] -> State -> State
instructionDupNHelper count instruction internalAccessor internalState =
if count > 0
then instructionDupNHelper (count - 1) instruction internalAccessor (internalState & accessor .~ (instruction : view accessor internalState))
else internalState
instructionSwap :: State -> Lens' State [a] -> State
instructionSwap state accessor =
state & accessor .~ swapper (view accessor state)
where
swapper :: [a] -> [a]
swapper (x1 : x2 : xs) = x2 : x1 : xs
swapper xs = xs
-- Rotates top 3 integers
-- We could use template haskell to rotate any number of these as
-- an instruction later. Template haskell seems very complicated tho.
instructionRot :: State -> Lens' State [a] -> State
instructionRot state accessor =
state & accessor .~ rotator (view accessor state)
where
rotator :: [a] -> [a]
rotator (x1 : x2 : x3 : xs) = x3 : x1 : x2 : xs
rotator xs = xs
instructionFlush :: State -> Lens' State [a] -> State
instructionFlush state accessor = state & accessor .~ []
instructionEq :: forall a. Eq a => State -> Lens' State [a] -> State
instructionEq state accessor =
case uncons stackTop of
Nothing -> state
Just (x1, x2 : _) -> state & bool .~ (x1 == x2) : view bool state & accessor .~ drop 2 (view accessor state)
Just _ -> state
where
stackTop :: [a]
stackTop = take 2 $ view accessor state
instructionStackDepth :: State -> Lens' State [a] -> State
instructionStackDepth state@(State {_int = is}) accessor = state{_int = length (view accessor state) : is}
instructionYankDup :: State -> Lens' State [a] -> State
instructionYankDup state@(State {_int = i : is}) accessor =
if notEmptyStack state accessor
then state{_int = is} & accessor .~ (view accessor state{_int = is} !! max 0 (min i (length (view accessor state{_int = is}) - 1))) : view accessor state{_int = is}
else state
instructionYankDup state _ = state
-- int non generic too
instructionYank :: forall a. State -> Lens' State [a] -> State
instructionYank state@(State {_int = i : is}) accessor =
let
myIndex :: Int
myIndex = max 0 (min i (length (view accessor state{_int = is}) - 1))
item :: a
item = view accessor state{_int = is} !! myIndex
deletedState :: State
deletedState = state{_int = is} & accessor .~ deleteAt myIndex (view accessor state{_int = is})
in
if notEmptyStack state{_int = is} accessor then deletedState & accessor .~ item : view accessor deletedState else state
instructionYank state _ = state
-- instructionShoveDup and instructionShove behave differently when indexing in such a way that
-- the duplicated index matters whether or not it's present in the stack at the moment of calculation.
-- I'm not going to keep this behavior. Check out interpysh examples for how pysh handles it.
instructionShoveDup :: State -> Lens' State [a] -> State
instructionShoveDup state@(State {_int = i : is}) accessor =
case uncons (view accessor state{_int = is}) of
Just (x,_) -> state{_int = is} & accessor .~ combineTuple x (splitAt (max 0 (min i (length (view accessor state{_int = is}) - 1))) (view accessor state{_int = is}))
_ -> state
instructionShoveDup state _ = state
instructionShove :: State -> Lens' State [a] -> State
instructionShove state accessor = instructionShoveDup state accessor & accessor .~ drop 1 (view accessor (instructionShoveDup state accessor))
-- not char generic
instructionConcat :: Semigroup a => State -> Lens' State [a] -> State
instructionConcat state accessor =
case uncons (view accessor state) of
Just (x1, x2:_) -> droppedState & accessor .~ (x1 <> x2) : view accessor droppedState
_ -> state
where
droppedState :: State
droppedState = state & accessor .~ drop 2 (view accessor state)
-- evolve fodder???????????
instructionNoOp :: State -> State
instructionNoOp state = state
instructionConj :: State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionConj state primAccessor vectorAccessor =
case (uncons (view primAccessor state), uncons (view vectorAccessor state)) of
(Just (p1,ps), Just (v1,vs)) -> state & primAccessor .~ ps & vectorAccessor .~ ((p1 : v1) : vs)
_ -> state
-- v for vector, vs for vectorstack (also applicable to strings)
-- Could abstract this unconsing even further in all functions below
instructionTakeN :: State -> Lens' State [[a]] -> State
instructionTakeN state@(State {_int = i1 : is}) accessor =
case uncons (view accessor state) of
Just (v1, vs) -> state{_int = is} & accessor .~ (take (absNum i1 v1) v1 : vs)
_ -> state
instructionTakeN state _ = state
instructionSubVector :: State -> Lens' State [[a]] -> State
instructionSubVector state@(State {_int = i1 : i2 : is}) accessor =
case uncons (view accessor state) of
Just (v1, vs) -> state{_int = is} & accessor .~ (subList i1 i2 v1 : vs)
_ -> state
instructionSubVector state _ = state
instructionVectorFirst :: State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorFirst state primAccessor vectorAccessor =
case uncons (view vectorAccessor state) of
Just (v1, vs) ->
case uncons v1 of
Just (vp1, _) -> state & primAccessor .~ (vp1 : view primAccessor state) & vectorAccessor .~ vs
_ -> state
_ -> state
instructionVectorLast :: State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorLast state primAccessor vectorAccessor =
case uncons (view vectorAccessor state) of
Just (v1, vs) ->
case uncons (drop (length v1 - 1) v1) of -- gonna keep this implementation over using last as this can't error
Just (vplast, _) -> state & primAccessor .~ (vplast : view primAccessor state) & vectorAccessor .~ vs
_ -> state
_ -> state
instructionVectorNth :: State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorNth state@(State {_int = i1 : is}) primAccessor vectorAccessor =
case uncons (view vectorAccessor state) of
Just (v1, vs) -> state{_int = is} & primAccessor .~ (v1 !! absNum i1 v1 : view primAccessor state{_int = is}) & vectorAccessor .~ vs
_ -> state
instructionVectorNth state _ _ = state
instructionRest :: State -> Lens' State [[a]] -> State
instructionRest state accessor =
case uncons (view accessor state) of
Just (v1, vs) -> state & accessor .~ (drop 1 v1 : vs)
_ -> state
instructionButLast :: State -> Lens' State [[a]] -> State
instructionButLast state accessor =
case uncons (view accessor state) of
Just (v1, vs) -> state & accessor .~ (safeInit v1 : vs)
_ -> state
instructionLength :: State -> Lens' State [[a]] -> State
instructionLength state@(State {_int = is}) accessor =
case uncons (view accessor state) of
Just (v1, vs) -> state{_int = length v1 : is} & accessor .~ vs
_ -> state
instructionReverse :: State -> Lens' State [[a]] -> State
instructionReverse state accessor =
case uncons (view accessor state) of
Just (v1, vs) -> state & accessor .~ (reverse v1 : vs)
_ -> state
instructionPushAll :: State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionPushAll state primAccessor vectorAccessor =
case uncons (view vectorAccessor state) of
Just (v1, vs) -> state & vectorAccessor .~ vs & primAccessor .~ (v1 <> view primAccessor state)
_ -> state
instructionVectorMakeEmpty :: State -> Lens' State [[a]] -> State
instructionVectorMakeEmpty state accessor = state & accessor .~ ([] : view accessor state)
instructionVectorIsEmpty :: State -> Lens' State [[a]] -> State
instructionVectorIsEmpty state@(State {_bool = bs}) accessor =
case uncons (view accessor state) of
Just (v1, vs) -> state{_bool = null v1 : bs} & accessor .~ vs
_ -> state
instructionVectorContains :: Eq a => State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorContains state@(State {_bool = bs}) primAccessor vectorAccessor =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, ps)) -> state{_bool = (findSubA v1 [p1] /= -1) : bs} & vectorAccessor .~ vs & primAccessor .~ ps
_ -> state
-- I couldn't think of a better way of doing this
instructionVectorIndexOf :: Eq a => State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorIndexOf state primAccessor vectorAccessor =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, ps)) -> (state & vectorAccessor .~ vs & primAccessor .~ ps) & int .~ (findSubA v1 [p1] : view int (state & vectorAccessor .~ vs & primAccessor .~ ps))
_ -> state
instructionVectorOccurrencesOf :: Eq a => State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorOccurrencesOf state primAccessor vectorAccessor =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, ps)) -> (state & vectorAccessor .~ vs & primAccessor .~ ps) & int .~ (amtOccurences v1 [p1] : view int (state & vectorAccessor .~ vs & primAccessor .~ ps))
_ -> state
instructionVectorSetNth :: State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorSetNth state@(State {_int = i1 : is}) primAccessor vectorAccessor =
case (uncons (view vectorAccessor state{_int = is}), uncons (view primAccessor state{_int = is})) of
(Just (v1, vs), Just (p1, ps)) -> state{_int = is} & vectorAccessor .~ (replaceAt (absNum i1 v1) p1 v1 : vs) & primAccessor .~ ps
_ -> state
instructionVectorSetNth state _ _ = state
instructionVectorReplace :: Eq a => State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorReplace state primAccessor vectorAccessor =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, p2 : ps)) -> state & vectorAccessor .~ (replace v1 [p1] [p2] Nothing : vs) & primAccessor .~ ps
_ -> state
instructionVectorReplaceFirst :: Eq a => State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorReplaceFirst state primAccessor vectorAccessor =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, p2 : ps)) -> state & vectorAccessor .~ (replace v1 [p1] [p2] (Just 1) : vs) & primAccessor .~ ps
_ -> state
instructionVectorRemove :: Eq a => State -> Lens' State [a] -> Lens' State [[a]] -> State
instructionVectorRemove state primAccessor vectorAccessor =
case (uncons (view vectorAccessor state), uncons (view primAccessor state)) of
(Just (v1, vs), Just (p1, ps)) -> state & vectorAccessor .~ (replace v1 [p1] [] Nothing : vs) & primAccessor .~ ps
_ -> state
instructionVectorIterate :: State -> Lens' State [a] -> Lens' State [[a]] -> ([a] -> Gene) -> (State -> State) -> State
instructionVectorIterate state@(State {_exec = e1 : es}) primAccessor vectorAccessor vectorType typeIterateFunction =
case uncons (view vectorAccessor state) of
Just ([], vs) -> state{_exec = es} & vectorAccessor .~ vs
Just ([x], vs) -> state & primAccessor .~ (x : view primAccessor state) & vectorAccessor .~ vs
Just (v1, vs) ->
(case uncons v1 of
Just (nv1, nvs) -> state{_exec = e1 : vectorType nvs : StateFunc typeIterateFunction : e1 : es} & primAccessor .~ (nv1 : view primAccessor state) & vectorAccessor .~ vs
_ -> state) -- This should never happen
_ -> state
instructionVectorIterate state _ _ _ _ = state
instructionCodeFrom :: State -> Lens' State [a] -> (a -> Gene) -> State
instructionCodeFrom state@(State {_code = cs}) accessor geneType =
case uncons (view accessor state) of
Just (x, xs) -> state{_code = geneType x : cs} & accessor .~ xs
_ -> state

View File

@ -1,104 +0,0 @@
module Instructions.IntInstructions where
import State
import Instructions.GenericInstructions
-- import Debug.Trace
instructionIntFromFloat :: State -> State
instructionIntFromFloat state@(State {_float = (f : fs), _int = is}) = state {_float = fs, _int = floor f : is}
instructionIntFromFloat state = state
instructionIntFromBool :: State -> State
instructionIntFromBool state@(State {_bool = (b : bs), _int = is}) = state {_bool = bs, _int = (if b then 1 else 0) : is}
instructionIntFromBool state = state
instructionIntAdd :: State -> State
instructionIntAdd state@(State {_int = (i1 : i2 : is)}) = state {_int = i2 + i1 : is}
instructionIntAdd state = state
instructionIntSub :: State -> State
instructionIntSub state@(State {_int = (i1 : i2 : is)}) = state {_int = i2 - i1 : is}
instructionIntSub state = state
instructionIntMul :: State -> State
instructionIntMul state@(State {_int = (i1 : i2 : is)}) = state {_int = i2 * i1 : is}
instructionIntMul state = state
instructionIntDiv :: State -> State
instructionIntDiv state@(State {_int = (i1 : i2 : is)}) = state {_int = if i1 /= 0 then (i2 `div` i1) : is else i1 : i2 : is}
instructionIntDiv state = state
instructionIntMod :: State -> State
instructionIntMod state@(State {_int = (i1 : i2 : is)}) = state {_int = i2 `mod` i1 : is}
instructionIntMod state = state
instructionIntMin :: State -> State
instructionIntMin state@(State {_int = (i1 : i2 : is)}) = state {_int = min i1 i2 : is}
instructionIntMin state = state
instructionIntMax :: State -> State
instructionIntMax state@(State {_int = (i1 : i2 : is)}) = state {_int = max i1 i2 : is}
instructionIntMax state = state
instructionIntInc :: State -> State
instructionIntInc state@(State {_int = (i1 : is)}) = state {_int = i1 + 1 : is}
instructionIntInc state = state
instructionIntDec :: State -> State
instructionIntDec state@(State {_int = (i1 : is)}) = state {_int = i1 - 1 : is}
instructionIntDec state = state
instructionIntLT :: State -> State
instructionIntLT state@(State {_int = i1 : i2 : is, _bool = bs}) = state {_int = is, _bool = (i1 < i2) : bs}
instructionIntLT state = state
instructionIntGT :: State -> State
instructionIntGT state@(State {_int = i1 : i2 : is, _bool = bs}) = state {_int = is, _bool = (i1 > i2) : bs}
instructionIntGT state = state
instructionIntLTE :: State -> State
instructionIntLTE state@(State {_int = i1 : i2 : is, _bool = bs}) = state {_int = is, _bool = (i1 <= i2) : bs}
instructionIntLTE state = state
instructionIntGTE :: State -> State
instructionIntGTE state@(State {_int = i1 : i2 : is, _bool = bs}) = state {_int = is, _bool = (i1 >= i2) : bs}
instructionIntGTE state = state
instructionIntDup :: State -> State
instructionIntDup state = instructionDup state int
instructionIntPop :: State -> State
instructionIntPop state = instructionPop state int
instructionIntDupN :: State -> State
instructionIntDupN state = instructionDupN state int
instructionIntSwap :: State -> State
instructionIntSwap state = instructionSwap state int
instructionIntRot :: State -> State
instructionIntRot state = instructionRot state int
instructionIntFlush :: State -> State
instructionIntFlush state = instructionFlush state int
instructionIntEq :: State -> State
instructionIntEq state = instructionEq state int
instructionIntStackDepth :: State -> State
instructionIntStackDepth state = instructionStackDepth state int
instructionIntYank :: State -> State
instructionIntYank state = instructionYank state int
instructionIntYankDup :: State -> State
instructionIntYankDup state = instructionYankDup state int
instructionIntShove :: State -> State
instructionIntShove state = instructionShove state int
instructionIntShoveDup :: State -> State
instructionIntShoveDup state = instructionShoveDup state int
instructionIntIsEmpty :: State -> State
instructionIntIsEmpty state = instructionIsEmpty state int

View File

@ -1,79 +0,0 @@
module Instructions.LogicalInstructions where
import State
import Instructions.GenericInstructions
instructionBoolFromInt :: State -> State
instructionBoolFromInt state@(State {_int = (i : is), _bool = bs}) = state {_int = is, _bool = (i /= 0) : bs}
instructionBoolFromInt state = state
instructionBoolFromFloat :: State -> State
instructionBoolFromFloat state@(State {_float = (f : fs), _bool = bs}) = state {_float = fs, _bool = (f /= 0) : bs}
instructionBoolFromFloat state = state
boolTemplate :: (Bool -> Bool -> Bool) -> State -> State
boolTemplate func state@(State {_bool = (b1 : b2 : bs)}) = state {_bool = func b1 b2 : bs}
boolTemplate _ state = state
instructionBoolAnd :: State -> State
instructionBoolAnd = boolTemplate (&&)
instructionBoolInvertFirstThenAnd :: State -> State
instructionBoolInvertFirstThenAnd state@(State {_bool = (b1 : bs)}) = boolTemplate (&&) state {_bool = not b1 : bs}
instructionBoolInvertFirstThenAnd state = state
instructionBoolInvertSecondThenAnd :: State -> State
instructionBoolInvertSecondThenAnd state@(State {_bool = (b1 : b2 : bs)}) = boolTemplate (&&) state {_bool = b1 : not b2 : bs}
instructionBoolInvertSecondThenAnd state = state
instructionBoolOr :: State -> State
instructionBoolOr = boolTemplate (||)
-- no builtin haskell xor moment
xor :: Bool -> Bool -> Bool
xor b1 b2
| b1 && not b2 = True
| not b1 && b2 = True
| otherwise = False
instructionBoolXor :: State -> State
instructionBoolXor = boolTemplate xor
instructionBoolPop :: State -> State
instructionBoolPop state = instructionPop state bool
instructionBoolDup :: State -> State
instructionBoolDup state = instructionDup state bool
instructionBoolDupN :: State -> State
instructionBoolDupN state = instructionDupN state bool
instructionBoolSwap :: State -> State
instructionBoolSwap state = instructionSwap state bool
instructionBoolRot :: State -> State
instructionBoolRot state = instructionRot state bool
instructionBoolFlush :: State -> State
instructionBoolFlush state = instructionFlush state bool
instructionBoolEq :: State -> State
instructionBoolEq state = instructionEq state bool
instructionBoolStackDepth :: State -> State
instructionBoolStackDepth state = instructionStackDepth state bool
instructionBoolYank :: State -> State
instructionBoolYank state = instructionYank state bool
instructionBoolYankDup :: State -> State
instructionBoolYankDup state = instructionYankDup state bool
instructionBoolShove :: State -> State
instructionBoolShove state = instructionShove state bool
instructionBoolShoveDup :: State -> State
instructionBoolShoveDup state = instructionShoveDup state bool
instructionBoolIsEmpty :: State -> State
instructionBoolIsEmpty state = instructionIsEmpty state bool

View File

@ -1,234 +0,0 @@
module Instructions.StringInstructions where
import State
import Instructions.GenericInstructions
import Data.List.Split
import Control.Lens
-- shamelessly stolen from https://hackage.haskell.org/package/MissingH-1.6.0.1/docs/src/Data.String.Utils.html#strip
wschars :: String
wschars = " \t\r\n"
strip :: String -> String
strip = lstrip . rstrip
lstrip :: String -> String
lstrip s = case s of
[] -> []
(x:xs) -> if x `elem` wschars
then lstrip xs
else s
-- this is a tad inefficient init
rstrip :: String -> String
rstrip = reverse . lstrip . reverse
instructionStringConcat :: State -> State
instructionStringConcat state = instructionConcat state string
instructionStringSwap :: State -> State
instructionStringSwap state = instructionSwap state string
instructionStringInsertString :: State -> State
instructionStringInsertString state@(State{_string = s1 : s2 : ss, _int = i1 : is}) = state {_string = combineTupleList s2 (splitAt i1 s1) : ss, _int = is}
instructionStringInsertString state = state
instructionStringFromFirstChar :: State -> State
instructionStringFromFirstChar state@(State {_string = (schar : _) : ss}) = state {_string = [schar] : ss}
instructionStringFromFirstChar state = state
instructionStringFromLastChar :: State -> State
instructionStringFromLastChar state@(State {_string = s1 : ss}) =
if not $ null s1
then state {_string = [last s1] : ss}
else state
instructionStringFromLastChar state = state
instructionStringFromNthChar :: State -> State
instructionStringFromNthChar state@(State {_string = s1 : ss, _int = i1 : is}) = state{_string = [s1 !! absNum i1 s1] : ss, _int = is}
instructionStringFromNthChar state = state
instructionStringIndexOfString :: State -> State
instructionStringIndexOfString state@(State {_string = s1 : s2 : ss, _int = is}) = state {_string = ss, _int = findSubA s1 s2 : is}
instructionStringIndexOfString state = state
instructionStringContainsString :: State -> State
instructionStringContainsString state@(State {_string = s1 : s2 : ss, _bool = bs}) = state {_string = ss, _bool = (findSubA s1 s2 /= -1) : bs}
instructionStringContainsString state = state
-- pysh reverses this. Check this for propeller
instructionStringSplitOnString :: State -> State
instructionStringSplitOnString state@(State {_string = s1 : s2 : ss}) = state {_string = reverse $ splitOn s2 s1 <> ss}
instructionStringSplitOnString state = state
instructionStringReplaceFirstString :: State -> State
instructionStringReplaceFirstString state@(State {_string = s1 : s2 : s3 : ss}) = state {_string = replace s1 s2 s3 (Just 1) : ss}
instructionStringReplaceFirstString state = state
instructionStringReplaceNString :: State -> State
instructionStringReplaceNString state@(State {_string = s1 : s2 : s3 : ss, _int = i1 : is}) = state{_string = replace s1 s2 s3 (Just i1) : ss, _int = is}
instructionStringReplaceNString state = state
instructionStringReplaceAllString :: State -> State
instructionStringReplaceAllString state@(State {_string = s1 : s2 : s3 : ss}) = state{_string = replace s1 s2 s3 Nothing : ss}
instructionStringReplaceAllString state = state
instructionStringRemoveFirstString :: State -> State
instructionStringRemoveFirstString state@(State {_string = s1 : s2 : ss}) = state{_string = replace s1 s2 "" (Just 1) : ss}
instructionStringRemoveFirstString state = state
instructionStringRemoveNString :: State -> State
instructionStringRemoveNString state@(State {_string = s1 : s2 : ss, _int = i1 : is}) = state{_string = replace s1 s2 "" (Just i1) : ss, _int = is}
instructionStringRemoveNString state = state
instructionStringRemoveAllString :: State -> State
instructionStringRemoveAllString state@(State {_string = s1 : s2 : ss}) = state{_string = replace s1 s2 "" Nothing : ss}
instructionStringRemoveAllString state = state
instructionStringOccurrencesOfString :: State -> State
instructionStringOccurrencesOfString state@(State {_string = s1 : s2 : ss, _int = is}) = state{_string = ss, _int = amtOccurences s1 s2 : is}
instructionStringOccurrencesOfString state = state
instructionStringInsertChar :: State -> State
instructionStringInsertChar state@(State {_string = s1 : ss, _char = c1 : cs, _int = i1 : is}) = state{_string = combineTuple c1 (splitAt i1 s1) : ss, _char = cs, _int = is}
instructionStringInsertChar state = state
instructionStringContainsChar :: State -> State
-- instructionStringContainsChar state@(State {_string = s1 : ss, _char = c1 : cs, _bool = bs}) = state{_string = ss, _char = cs, _bool = (findSubA s1 [c1] /= -1) : bs}
-- instructionStringContainsChar state = state
instructionStringContainsChar state = instructionVectorContains state char string
instructionStringIndexOfChar :: State -> State
instructionStringIndexOfChar state = instructionVectorIndexOf state char string
instructionStringSplitOnChar :: State -> State
instructionStringSplitOnChar state@(State {_string = s1 : ss, _char = c1 : cs}) = state {_string = reverse $ splitOn [c1] s1 <> ss, _char = cs}
instructionStringSplitOnChar state = state
instructionStringReplaceFirstChar :: State -> State
instructionStringReplaceFirstChar state = instructionVectorReplaceFirst state char string
instructionStringReplaceNChar :: State -> State
instructionStringReplaceNChar state@(State {_string = s1 : ss, _char = c1 : c2 : cs, _int = i1 : is}) = state{_string = replace s1 [c1] [c2] (Just i1) : ss, _char = cs, _int = is}
instructionStringReplaceNChar state = state
instructionStringReplaceAllChar :: State -> State
instructionStringReplaceAllChar state = instructionVectorReplace state char string
instructionStringRemoveFirstChar :: State -> State
instructionStringRemoveFirstChar state@(State {_string = s1 : ss, _char = c1 : cs}) = state {_string = replace s1 [c1] "" (Just 1) : ss, _char = cs}
instructionStringRemoveFirstChar state = state
instructionStringRemoveNChar :: State -> State
instructionStringRemoveNChar state@(State {_string = s1 : ss, _char = c1 : cs, _int = i1 : is}) = state{_string = replace s1 [c1] "" (Just i1) : ss, _char = cs, _int = is}
instructionStringRemoveNChar state = state
instructionStringRemoveAllChar :: State -> State
instructionStringRemoveAllChar state = instructionVectorRemove state char string
instructionStringOccurrencesOfChar :: State -> State
instructionStringOccurrencesOfChar state = instructionVectorOccurrencesOf state char string
instructionStringReverse :: State -> State
instructionStringReverse state = instructionReverse state string
instructionStringHead :: State -> State
instructionStringHead state = instructionTakeN state string
instructionStringTail :: State -> State
instructionStringTail state@(State {_string = s1 : ss, _int = i1 : is}) = state{_string = takeR (absNum i1 s1) s1 : ss, _int = is}
instructionStringTail state = state
instructionStringAppendChar :: State -> State
instructionStringAppendChar state = instructionConj state char string
instructionStringRest :: State -> State
instructionStringRest state = instructionRest state string
instructionStringButLast :: State -> State
instructionStringButLast state = instructionButLast state string
instructionStringDrop :: State -> State
instructionStringDrop state@(State {_string = s1 : ss, _int = i1 : is}) = state{_string = drop (absNum i1 s1) s1 : ss, _int = is}
instructionStringDrop state = state
instructionStringButLastN :: State -> State
instructionStringButLastN state@(State {_string = s1 : ss, _int = i1 : is}) = state{_string = dropR (absNum i1 s1) s1 : ss, _int = is}
instructionStringButLastN state = state
instructionStringLength :: State -> State
instructionStringLength state = instructionLength state string
instructionStringMakeEmpty :: State -> State
instructionStringMakeEmpty state = instructionVectorMakeEmpty state string
instructionStringIsEmptyString :: State -> State
instructionStringIsEmptyString state@(State {_string = s1 : ss, _bool = bs}) = state{_string = ss, _bool = null s1 : bs}
instructionStringIsEmptyString state = state
instructionStringRemoveNth :: State -> State
instructionStringRemoveNth state@(State {_string = s1 : ss, _int = i1 : is}) = state{_string = deleteAt (absNum i1 s1) s1 : ss, _int = is}
instructionStringRemoveNth state = state
instructionStringSetNth :: State -> State
instructionStringSetNth state = instructionVectorSetNth state char string
instructionStringStripWhitespace :: State -> State
instructionStringStripWhitespace state@(State {_string = s1 : ss}) = state{_string = strip s1 : ss}
instructionStringStripWhitespace state = state
-- Need to do uncons to all of the warnings in this mug
instructionStringFromLens :: Show a => State -> Lens' State [a] -> State
instructionStringFromLens state@(State {_string = ss}) accessor =
case uncons (view accessor state) of
Nothing -> state
Just (x,_) -> state{_string = show x : ss}
instructionStringFromBool :: State -> State
instructionStringFromBool state = instructionStringFromLens state bool
instructionStringFromInt :: State -> State
instructionStringFromInt state = instructionStringFromLens state int
instructionStringFromFloat :: State -> State
instructionStringFromFloat state = instructionStringFromLens state float
instructionStringFromChar :: State -> State
instructionStringFromChar state@(State {_string = ss, _char = c1 : cs}) = state{_string = [c1] : ss, _char = cs}
instructionStringFromChar state = state
instructionStringPop :: State -> State
instructionStringPop state = instructionPop state string
instructionStringDup :: State -> State
instructionStringDup state = instructionDup state string
instructionStringDupN :: State -> State
instructionStringDupN state = instructionDupN state string
instructionStringRot :: State -> State
instructionStringRot state = instructionRot state string
instructionStringFlush :: State -> State
instructionStringFlush state = instructionFlush state string
instructionStringEq :: State -> State
instructionStringEq state = instructionEq state string
instructionStringStackDepth :: State -> State
instructionStringStackDepth state = instructionStackDepth state string
instructionStringYank :: State -> State
instructionStringYank state = instructionYank state string
instructionStringYankDup :: State -> State
instructionStringYankDup state = instructionYankDup state string
instructionStringIsEmpty :: State -> State
instructionStringIsEmpty state = instructionIsEmpty state string
instructionStringShove :: State -> State
instructionStringShove state = instructionShove state string
instructionStringShoveDup :: State -> State
instructionStringShoveDup state = instructionShoveDup state string

View File

@ -1,106 +0,0 @@
module Instructions.VectorCharInstructions where
import State
import Instructions.GenericInstructions
instructionVectorCharConcat :: State -> State
instructionVectorCharConcat state = instructionConcat state vectorChar
instructionVectorCharConj :: State -> State
instructionVectorCharConj state = instructionConj state char vectorChar
instructionVectorCharTakeN :: State -> State
instructionVectorCharTakeN state = instructionTakeN state vectorChar
instructionVectorCharSubVector :: State -> State
instructionVectorCharSubVector state = instructionSubVector state vectorChar
instructionVectorCharFirst :: State -> State
instructionVectorCharFirst state = instructionVectorFirst state char vectorChar
instructionVectorCharLast :: State -> State
instructionVectorCharLast state = instructionVectorLast state char vectorChar
instructionVectorCharNth :: State -> State
instructionVectorCharNth state = instructionVectorNth state char vectorChar
instructionVectorCharRest :: State -> State
instructionVectorCharRest state = instructionRest state vectorChar
instructionVectorCharButLast :: State -> State
instructionVectorCharButLast state = instructionButLast state vectorChar
instructionVectorCharLength :: State -> State
instructionVectorCharLength state = instructionLength state vectorChar
instructionVectorCharReverse :: State -> State
instructionVectorCharReverse state = instructionReverse state vectorChar
instructionVectorCharPushAll :: State -> State
instructionVectorCharPushAll state = instructionPushAll state char vectorChar
instructionVectorCharMakeEmpty :: State -> State
instructionVectorCharMakeEmpty state = instructionVectorMakeEmpty state vectorChar
instructionVectorCharIsEmpty :: State -> State
instructionVectorCharIsEmpty state = instructionVectorIsEmpty state vectorChar
instructionVectorCharIndexOf :: State -> State
instructionVectorCharIndexOf state = instructionVectorIndexOf state char vectorChar
instructionVectorCharOccurrencesOf :: State -> State
instructionVectorCharOccurrencesOf state = instructionVectorOccurrencesOf state char vectorChar
instructionVectorCharSetNth :: State -> State
instructionVectorCharSetNth state = instructionVectorSetNth state char vectorChar
instructionVectorCharReplace :: State -> State
instructionVectorCharReplace state = instructionVectorReplace state char vectorChar
instructionVectorCharReplaceFirst :: State -> State
instructionVectorCharReplaceFirst state = instructionVectorReplaceFirst state char vectorChar
instructionVectorCharRemove :: State -> State
instructionVectorCharRemove state = instructionVectorRemove state char vectorChar
instructionVectorCharIterate :: State -> State
instructionVectorCharIterate state = instructionVectorIterate state char vectorChar GeneVectorChar instructionVectorCharIterate
instructionVectorCharPop :: State -> State
instructionVectorCharPop state = instructionPop state vectorChar
instructionVectorCharDup :: State -> State
instructionVectorCharDup state = instructionDup state vectorChar
instructionVectorCharDupN :: State -> State
instructionVectorCharDupN state = instructionDupN state vectorChar
instructionVectorCharSwap :: State -> State
instructionVectorCharSwap state = instructionSwap state vectorChar
instructionVectorCharRot :: State -> State
instructionVectorCharRot state = instructionRot state vectorChar
instructionVectorCharFlush :: State -> State
instructionVectorCharFlush state = instructionFlush state vectorChar
instructionVectorCharEq :: State -> State
instructionVectorCharEq state = instructionEq state vectorChar
instructionVectorCharStackDepth :: State -> State
instructionVectorCharStackDepth state = instructionStackDepth state vectorChar
instructionVectorCharYank :: State -> State
instructionVectorCharYank state = instructionYank state vectorChar
instructionVectorCharYankDup :: State -> State
instructionVectorCharYankDup state = instructionYankDup state vectorChar
instructionVectorCharStackIsEmpty :: State -> State
instructionVectorCharStackIsEmpty state = instructionIsEmpty state vectorChar
instructionVectorCharShove :: State -> State
instructionVectorCharShove state = instructionShove state vectorChar
instructionVectorCharShoveDup :: State -> State
instructionVectorCharShoveDup state = instructionShoveDup state vectorChar

View File

@ -1,106 +0,0 @@
module Instructions.VectorFloatInstructions where
import State
import Instructions.GenericInstructions
instructionVectorFloatConcat :: State -> State
instructionVectorFloatConcat state = instructionConcat state vectorFloat
instructionVectorFloatConj :: State -> State
instructionVectorFloatConj state = instructionConj state float vectorFloat
instructionVectorFloatTakeN :: State -> State
instructionVectorFloatTakeN state = instructionTakeN state vectorFloat
instructionVectorFloatSubVector :: State -> State
instructionVectorFloatSubVector state = instructionSubVector state vectorFloat
instructionVectorFloatFirst :: State -> State
instructionVectorFloatFirst state = instructionVectorFirst state float vectorFloat
instructionVectorFloatLast :: State -> State
instructionVectorFloatLast state = instructionVectorLast state float vectorFloat
instructionVectorFloatNth :: State -> State
instructionVectorFloatNth state = instructionVectorNth state float vectorFloat
instructionVectorFloatRest :: State -> State
instructionVectorFloatRest state = instructionRest state vectorFloat
instructionVectorFloatButLast :: State -> State
instructionVectorFloatButLast state = instructionButLast state vectorFloat
instructionVectorFloatLength :: State -> State
instructionVectorFloatLength state = instructionLength state vectorFloat
instructionVectorFloatReverse :: State -> State
instructionVectorFloatReverse state = instructionReverse state vectorFloat
instructionVectorFloatPushAll :: State -> State
instructionVectorFloatPushAll state = instructionPushAll state float vectorFloat
instructionVectorFloatMakeEmpty :: State -> State
instructionVectorFloatMakeEmpty state = instructionVectorMakeEmpty state vectorFloat
instructionVectorFloatIsEmpty :: State -> State
instructionVectorFloatIsEmpty state = instructionVectorIsEmpty state vectorFloat
instructionVectorFloatIndexOf :: State -> State
instructionVectorFloatIndexOf state = instructionVectorIndexOf state float vectorFloat
instructionVectorFloatOccurrencesOf :: State -> State
instructionVectorFloatOccurrencesOf state = instructionVectorOccurrencesOf state float vectorFloat
instructionVectorFloatSetNth :: State -> State
instructionVectorFloatSetNth state = instructionVectorSetNth state float vectorFloat
instructionVectorFloatReplace :: State -> State
instructionVectorFloatReplace state = instructionVectorReplace state float vectorFloat
instructionVectorFloatReplaceFirst :: State -> State
instructionVectorFloatReplaceFirst state = instructionVectorReplaceFirst state float vectorFloat
instructionVectorFloatRemove :: State -> State
instructionVectorFloatRemove state = instructionVectorRemove state float vectorFloat
instructionVectorFloatIterate :: State -> State
instructionVectorFloatIterate state = instructionVectorIterate state float vectorFloat GeneVectorFloat instructionVectorFloatIterate
instructionVectorFloatPop :: State -> State
instructionVectorFloatPop state = instructionPop state vectorFloat
instructionVectorFloatDup :: State -> State
instructionVectorFloatDup state = instructionDup state vectorFloat
instructionVectorFloatDupN :: State -> State
instructionVectorFloatDupN state = instructionDupN state vectorFloat
instructionVectorFloatSwap :: State -> State
instructionVectorFloatSwap state = instructionSwap state vectorFloat
instructionVectorFloatRot :: State -> State
instructionVectorFloatRot state = instructionRot state vectorFloat
instructionVectorFloatFlush :: State -> State
instructionVectorFloatFlush state = instructionFlush state vectorFloat
instructionVectorFloatEq :: State -> State
instructionVectorFloatEq state = instructionEq state vectorFloat
instructionVectorFloatStackDepth :: State -> State
instructionVectorFloatStackDepth state = instructionStackDepth state vectorFloat
instructionVectorFloatYank :: State -> State
instructionVectorFloatYank state = instructionYank state vectorFloat
instructionVectorFloatYankDup :: State -> State
instructionVectorFloatYankDup state = instructionYankDup state vectorFloat
instructionVectorFloatStackIsEmpty :: State -> State
instructionVectorFloatStackIsEmpty state = instructionIsEmpty state vectorFloat
instructionVectorFloatShove :: State -> State
instructionVectorFloatShove state = instructionShove state vectorFloat
instructionVectorFloatShoveDup :: State -> State
instructionVectorFloatShoveDup state = instructionShoveDup state vectorFloat

View File

@ -1,106 +0,0 @@
module Instructions.VectorIntInstructions where
import Instructions.GenericInstructions
import State
instructionVectorIntConcat :: State -> State
instructionVectorIntConcat state = instructionConcat state vectorInt
instructionVectorIntConj :: State -> State
instructionVectorIntConj state = instructionConj state int vectorInt
instructionVectorIntTakeN :: State -> State
instructionVectorIntTakeN state = instructionTakeN state vectorInt
instructionVectorIntSubVector :: State -> State
instructionVectorIntSubVector state = instructionSubVector state vectorInt
instructionVectorIntFirst :: State -> State
instructionVectorIntFirst state = instructionVectorFirst state int vectorInt
instructionVectorIntLast :: State -> State
instructionVectorIntLast state = instructionVectorLast state int vectorInt
instructionVectorIntNth :: State -> State
instructionVectorIntNth state = instructionVectorNth state int vectorInt
instructionVectorIntRest :: State -> State
instructionVectorIntRest state = instructionRest state vectorInt
instructionVectorIntButLast :: State -> State
instructionVectorIntButLast state = instructionButLast state vectorInt
instructionVectorIntLength :: State -> State
instructionVectorIntLength state = instructionLength state vectorInt
instructionVectorIntReverse :: State -> State
instructionVectorIntReverse state = instructionReverse state vectorInt
instructionVectorIntPushAll :: State -> State
instructionVectorIntPushAll state = instructionPushAll state int vectorInt
instructionVectorIntMakeEmpty :: State -> State
instructionVectorIntMakeEmpty state = instructionVectorMakeEmpty state vectorInt
instructionVectorIntIsEmpty :: State -> State
instructionVectorIntIsEmpty state = instructionVectorIsEmpty state vectorInt
instructionVectorIntIndexOf :: State -> State
instructionVectorIntIndexOf state = instructionVectorIndexOf state int vectorInt
instructionVectorIntOccurrencesOf :: State -> State
instructionVectorIntOccurrencesOf state = instructionVectorOccurrencesOf state int vectorInt
instructionVectorIntSetNth :: State -> State
instructionVectorIntSetNth state = instructionVectorSetNth state int vectorInt
instructionVectorIntReplace :: State -> State
instructionVectorIntReplace state = instructionVectorReplace state int vectorInt
instructionVectorIntReplaceFirst :: State -> State
instructionVectorIntReplaceFirst state = instructionVectorReplaceFirst state int vectorInt
instructionVectorIntRemove :: State -> State
instructionVectorIntRemove state = instructionVectorRemove state int vectorInt
instructionVectorIntIterate :: State -> State
instructionVectorIntIterate state = instructionVectorIterate state int vectorInt GeneVectorInt instructionVectorIntIterate
instructionVectorIntPop :: State -> State
instructionVectorIntPop state = instructionPop state vectorChar
instructionVectorIntDup :: State -> State
instructionVectorIntDup state = instructionDup state vectorChar
instructionVectorIntDupN :: State -> State
instructionVectorIntDupN state = instructionDupN state vectorChar
instructionVectorIntSwap :: State -> State
instructionVectorIntSwap state = instructionSwap state vectorChar
instructionVectorIntRot :: State -> State
instructionVectorIntRot state = instructionRot state vectorChar
instructionVectorIntFlush :: State -> State
instructionVectorIntFlush state = instructionFlush state vectorChar
instructionVectorIntEq :: State -> State
instructionVectorIntEq state = instructionEq state vectorChar
instructionVectorIntStackDepth :: State -> State
instructionVectorIntStackDepth state = instructionStackDepth state vectorChar
instructionVectorIntYank :: State -> State
instructionVectorIntYank state = instructionYank state vectorChar
instructionVectorIntYankDup :: State -> State
instructionVectorIntYankDup state = instructionYankDup state vectorChar
instructionVectorIntStackIsEmpty :: State -> State
instructionVectorIntStackIsEmpty state = instructionIsEmpty state vectorChar
instructionVectorIntShove :: State -> State
instructionVectorIntShove state = instructionShove state vectorChar
instructionVectorIntShoveDup :: State -> State
instructionVectorIntShoveDup state = instructionShoveDup state vectorChar

View File

@ -1,106 +0,0 @@
module Instructions.VectorLogicalInstructions where
import State
import Instructions.GenericInstructions
instructionVectorBoolConcat :: State -> State
instructionVectorBoolConcat state = instructionConcat state vectorBool
instructionVectorBoolConj :: State -> State
instructionVectorBoolConj state = instructionConj state bool vectorBool
instructionVectorBoolTakeN :: State -> State
instructionVectorBoolTakeN state = instructionTakeN state vectorBool
instructionVectorBoolSubVector :: State -> State
instructionVectorBoolSubVector state = instructionSubVector state vectorBool
instructionVectorBoolFirst :: State -> State
instructionVectorBoolFirst state = instructionVectorFirst state bool vectorBool
instructionVectorBoolLast :: State -> State
instructionVectorBoolLast state = instructionVectorLast state bool vectorBool
instructionVectorBoolNth :: State -> State
instructionVectorBoolNth state = instructionVectorNth state bool vectorBool
instructionVectorBoolRest :: State -> State
instructionVectorBoolRest state = instructionRest state vectorBool
instructionVectorBoolButLast :: State -> State
instructionVectorBoolButLast state = instructionButLast state vectorBool
instructionVectorBoolLength :: State -> State
instructionVectorBoolLength state = instructionLength state vectorBool
instructionVectorBoolReverse :: State -> State
instructionVectorBoolReverse state = instructionReverse state vectorBool
instructionVectorBoolPushAll :: State -> State
instructionVectorBoolPushAll state = instructionPushAll state bool vectorBool
instructionVectorBoolMakeEmpty :: State -> State
instructionVectorBoolMakeEmpty state = instructionVectorMakeEmpty state vectorBool
instructionVectorBoolIsEmpty :: State -> State
instructionVectorBoolIsEmpty state = instructionVectorIsEmpty state vectorBool
instructionVectorBoolIndexOf :: State -> State
instructionVectorBoolIndexOf state = instructionVectorIndexOf state bool vectorBool
instructionVectorBoolOccurrencesOf :: State -> State
instructionVectorBoolOccurrencesOf state = instructionVectorOccurrencesOf state bool vectorBool
instructionVectorBoolSetNth :: State -> State
instructionVectorBoolSetNth state = instructionVectorSetNth state bool vectorBool
instructionVectorBoolReplace :: State -> State
instructionVectorBoolReplace state = instructionVectorReplace state bool vectorBool
instructionVectorBoolReplaceFirst :: State -> State
instructionVectorBoolReplaceFirst state = instructionVectorReplaceFirst state bool vectorBool
instructionVectorBoolRemove :: State -> State
instructionVectorBoolRemove state = instructionVectorRemove state bool vectorBool
instructionVectorBoolIterate :: State -> State
instructionVectorBoolIterate state = instructionVectorIterate state bool vectorBool GeneVectorBool instructionVectorBoolIterate
instructionVectorBoolPop :: State -> State
instructionVectorBoolPop state = instructionPop state vectorBool
instructionVectorBoolDup :: State -> State
instructionVectorBoolDup state = instructionDup state vectorBool
instructionVectorBoolDupN :: State -> State
instructionVectorBoolDupN state = instructionDupN state vectorBool
instructionVectorBoolSwap :: State -> State
instructionVectorBoolSwap state = instructionSwap state vectorBool
instructionVectorBoolRot :: State -> State
instructionVectorBoolRot state = instructionRot state vectorBool
instructionVectorBoolFlush :: State -> State
instructionVectorBoolFlush state = instructionFlush state vectorBool
instructionVectorBoolEq :: State -> State
instructionVectorBoolEq state = instructionEq state vectorBool
instructionVectorBoolStackDepth :: State -> State
instructionVectorBoolStackDepth state = instructionStackDepth state vectorBool
instructionVectorBoolYank :: State -> State
instructionVectorBoolYank state = instructionYank state vectorBool
instructionVectorBoolYankDup :: State -> State
instructionVectorBoolYankDup state = instructionYankDup state vectorBool
instructionVectorBoolStackIsEmpty :: State -> State
instructionVectorBoolStackIsEmpty state = instructionIsEmpty state vectorBool
instructionVectorBoolShove :: State -> State
instructionVectorBoolShove state = instructionShove state vectorBool
instructionVectorBoolShoveDup :: State -> State
instructionVectorBoolShoveDup state = instructionShoveDup state vectorBool

View File

@ -1,106 +0,0 @@
module Instructions.VectorStringInstructions where
import State
import Instructions.GenericInstructions
instructionVectorStringConcat :: State -> State
instructionVectorStringConcat state = instructionConcat state vectorString
instructionVectorStringConj :: State -> State
instructionVectorStringConj state = instructionConj state string vectorString
instructionVectorStringTakeN :: State -> State
instructionVectorStringTakeN state = instructionTakeN state vectorString
instructionVectorStringSubVector :: State -> State
instructionVectorStringSubVector state = instructionSubVector state vectorString
instructionVectorStringFirst :: State -> State
instructionVectorStringFirst state = instructionVectorFirst state string vectorString
instructionVectorStringLast :: State -> State
instructionVectorStringLast state = instructionVectorLast state string vectorString
instructionVectorStringNth :: State -> State
instructionVectorStringNth state = instructionVectorNth state string vectorString
instructionVectorStringRest :: State -> State
instructionVectorStringRest state = instructionRest state vectorString
instructionVectorStringButLast :: State -> State
instructionVectorStringButLast state = instructionButLast state vectorString
instructionVectorStringLength :: State -> State
instructionVectorStringLength state = instructionLength state vectorString
instructionVectorStringReverse :: State -> State
instructionVectorStringReverse state = instructionReverse state vectorString
instructionVectorStringPushAll :: State -> State
instructionVectorStringPushAll state = instructionPushAll state string vectorString
instructionVectorStringMakeEmpty :: State -> State
instructionVectorStringMakeEmpty state = instructionVectorMakeEmpty state vectorString
instructionVectorStringIsEmpty :: State -> State
instructionVectorStringIsEmpty state = instructionVectorIsEmpty state vectorString
instructionVectorStringIndexOf :: State -> State
instructionVectorStringIndexOf state = instructionVectorIndexOf state string vectorString
instructionVectorStringOccurrencesOf :: State -> State
instructionVectorStringOccurrencesOf state = instructionVectorOccurrencesOf state string vectorString
instructionVectorStringSetNth :: State -> State
instructionVectorStringSetNth state = instructionVectorSetNth state string vectorString
instructionVectorStringReplace :: State -> State
instructionVectorStringReplace state = instructionVectorReplace state string vectorString
instructionVectorStringReplaceFirst :: State -> State
instructionVectorStringReplaceFirst state = instructionVectorReplaceFirst state string vectorString
instructionVectorStringRemove :: State -> State
instructionVectorStringRemove state = instructionVectorRemove state string vectorString
instructionVectorStringIterate :: State -> State
instructionVectorStringIterate state = instructionVectorIterate state string vectorString GeneVectorString instructionVectorStringIterate
instructionVectorStringPop :: State -> State
instructionVectorStringPop state = instructionPop state vectorString
instructionVectorStringDup :: State -> State
instructionVectorStringDup state = instructionDup state vectorString
instructionVectorStringDupN :: State -> State
instructionVectorStringDupN state = instructionDupN state vectorString
instructionVectorStringSwap :: State -> State
instructionVectorStringSwap state = instructionSwap state vectorString
instructionVectorStringRot :: State -> State
instructionVectorStringRot state = instructionRot state vectorString
instructionVectorStringFlush :: State -> State
instructionVectorStringFlush state = instructionFlush state vectorString
instructionVectorStringEq :: State -> State
instructionVectorStringEq state = instructionEq state vectorString
instructionVectorStringStackDepth :: State -> State
instructionVectorStringStackDepth state = instructionStackDepth state vectorString
instructionVectorStringYank :: State -> State
instructionVectorStringYank state = instructionYank state vectorString
instructionVectorStringYankDup :: State -> State
instructionVectorStringYankDup state = instructionYankDup state vectorString
instructionVectorStringStackIsEmpty :: State -> State
instructionVectorStringStackIsEmpty state = instructionIsEmpty state vectorString
instructionVectorStringShove :: State -> State
instructionVectorStringShove state = instructionShove state vectorString
instructionVectorStringShoveDup :: State -> State
instructionVectorStringShoveDup state = instructionShoveDup state vectorString

View File

@ -1,70 +0,0 @@
module Push where
import Control.Lens
import Data.Map qualified as Map
-- import Instructions.IntInstructions
-- import Instructions.ExecInstructions
import State
-- import Debug.Trace (trace, traceStack)
-- Each core func should be: (State -> State -> State)
-- but each core function can use abstract helper functions.
-- That is more efficient than checking length.
-- Everntually, this can be part of the apply func to state helpers,
-- which should take the number and type of parameter they have.
-- This is one of the push genome functions itself, not infrastructure.
-- Optionally, split this off into independent functions
instructionParameterLoad :: State -> State
instructionParameterLoad state@(State {_parameter = (p : _)}) = case p of
(GeneInt val) -> state & int .~ val : view int state
(GeneFloat val) -> state & float .~ val : view float state
(GeneBool val) -> state & bool .~ val : view bool state
(GeneString val) -> state & string .~ val : view string state
(GeneChar val) -> state & char .~ val : view char state
(GeneVectorInt val) -> state & vectorInt .~ val : view vectorInt state
(GeneVectorFloat val) -> state & vectorFloat .~ val : view vectorFloat state
(GeneVectorBool val) -> state & vectorBool .~ val : view vectorBool state
(GeneVectorString val) -> state & vectorString .~ val : view vectorString state
(GeneVectorChar val) -> state & vectorChar .~ val : view vectorChar state
(StateFunc _) -> undefined
(PlaceInput _) -> undefined
Close -> undefined
(Block xs) -> state & exec .~ xs <> view exec state
instructionParameterLoad state = state
-- Loads a genome into the exec stack
loadProgram :: [Gene] -> State -> State
loadProgram newstack state = state & exec .~ newstack
-- Takes a Push state, and generates the next push state via:
-- If the first item on the EXEC stack is a single instruction
-- then pop it and execute it.
-- Else if the first item on the EXEC stack is a literal
-- then pop it and push it onto the appropriate stack.
-- Else (the first item must be a list) pop it and push all of the
-- items that it contains back onto the EXEC stack individually,
-- in reverse order (so that the item that was first in the list
-- ends up on top).
-- The empty-stack safety of interpretExec on empty stacks depends on the functions it calls.
interpretExec :: State -> State
interpretExec state@(State {_exec = e : es}) =
case e of
(GeneInt val) -> interpretExec (state & exec .~ es & int .~ val : view int state)
(GeneFloat val) -> interpretExec (state & exec .~ es & float .~ val : view float state)
(GeneBool val) -> interpretExec (state & exec .~ es & bool .~ val : view bool state)
(GeneString val) -> interpretExec (state & exec .~ es & string .~ val : view string state)
(GeneChar val) -> interpretExec (state & exec .~ es & char .~ val : view char state)
(GeneVectorInt val) -> interpretExec (state & exec .~ es & vectorInt .~ val : view vectorInt state)
(GeneVectorFloat val) -> interpretExec (state & exec .~ es & vectorFloat .~ val : view vectorFloat state)
(GeneVectorBool val) -> interpretExec (state & exec .~ es & vectorBool .~ val : view vectorBool state)
(GeneVectorString val) -> interpretExec (state & exec .~ es & vectorString .~ val : view vectorString state)
(GeneVectorChar val) -> interpretExec (state & exec .~ es & vectorChar .~ val : view vectorChar state)
(StateFunc func) -> interpretExec $ func state {_exec = es}
(Block block) -> interpretExec (state {_exec = block ++ es})
(PlaceInput val) -> interpretExec (state {_exec = (view input state Map.! val) : es})
Close -> undefined -- This should be removed later. Will be converted to Blocks in the Plushy -> Exec stack process
interpretExec state = state
-- Need to make interpretExec strict, right?

View File

@ -1,117 +0,0 @@
{-# LANGUAGE TemplateHaskell #-}
module State where
import Control.Lens
import Data.Map qualified as Map
-- The exec stack must store heterogenous types,
-- and we must be able to detect that type at runtime.
-- One solution is for the exec stack to be a list of [Gene].
-- The parameter stack could be singular [Gene] or multiple [atomic] types.
data Gene
= GeneInt Int
| GeneFloat Float
| GeneBool Bool
| GeneString String
| GeneChar Char
| GeneVectorInt [Int]
| GeneVectorFloat [Float]
| GeneVectorBool [Bool]
| GeneVectorString [String]
| GeneVectorChar [Char]
| StateFunc (State -> State)
| PlaceInput String
| Close
| Block [Gene]
instance Eq Gene where
GeneInt x == GeneInt y = x == y
GeneFloat x == GeneFloat y = x == y
GeneBool x == GeneBool y = x == y
GeneString x == GeneString y = x == y
GeneChar x == GeneChar y = x == y
PlaceInput x == PlaceInput y = x == y
GeneVectorInt xs == GeneVectorInt ys = xs == ys
GeneVectorFloat xs == GeneVectorFloat ys = xs == ys
GeneVectorBool xs == GeneVectorBool ys = xs == ys
GeneVectorString xs == GeneVectorString ys = xs == ys
GeneVectorChar xs == GeneVectorChar ys = xs == ys
Close == Close = True
StateFunc _ == StateFunc _ = True -- This line is probably not the best thing to do
Block x == Block y = x == y
_ == _ = False
instance Show Gene where
show (GeneInt x) = "Int: " <> show x
show (GeneFloat x) = "Float: " <> show x
show (GeneBool x) = "Bool: " <> show x
show (GeneString x) = "String: " <> x
show (GeneChar x) = "Char: " <> show x
show (StateFunc _) = "Func: unnamed"
show (PlaceInput x) = "In: " <> x
show (GeneVectorInt xs) = "Int Vec: " <> show xs
show (GeneVectorFloat xs) = "Float Vec: " <> show xs
show (GeneVectorBool xs) = "Bool Vec: " <> show xs
show (GeneVectorString xs) = "String Vec: " <> show xs
show (GeneVectorChar xs) = "Char Vec: " <> show xs
show Close = "Close"
show (Block xs) = "Block: " <> show xs
data State = State
{ _exec :: [Gene],
_code :: [Gene],
_int :: [Int],
_float :: [Float],
_bool :: [Bool],
_string :: [String],
_char :: [Char],
_vectorInt :: [[Int]],
_vectorFloat :: [[Float]],
_vectorBool :: [[Bool]],
_vectorString :: [[String]],
_vectorChar :: [[Char]],
_parameter :: [Gene],
_input :: Map.Map String Gene
}
deriving (Show, Eq)
$(makeLenses ''State)
emptyState :: State
emptyState =
State
{ _exec = [],
_code = [],
_int = [],
_float = [],
_bool = [],
_string = [],
_char = [],
_parameter = [],
_vectorInt = [],
_vectorFloat = [],
_vectorBool = [],
_vectorString = [],
_vectorChar = [],
_input = Map.empty
}
exampleState :: State
exampleState =
State
{ _exec = [],
_code = [],
_int = [32, 56],
_float = [3.23, 9.235],
_bool = [True, False],
_string = ["abc", "123"],
_char = ['d', 'e', 'f'],
_parameter = [],
_vectorInt = [[1, 2], [5, 6, 8]],
_vectorFloat = [[1.234, 9.21], [5.42, 6.221, 8.5493]],
_vectorBool = [[True, False], [False, False, True]],
_vectorString = [["this is a sentence", "this is also a sentence"], ["s0", "s1", "s2"]],
_vectorChar = [['z', 'x'], ['r', 'a', 't', 'l']],
_input = Map.empty
}

View File

@ -1,323 +1,41 @@
import Control.Exception (assert)
import Instructions
import Push
import State
-- import HushGP.Instructions
-- import HushGP.Push
import HushGP.PushTests
-- import HushGP.State
import Test.QuickCheck
-- import Data.List
-- import Control.Lens
-- import Debug.Trace
-- TODO: Need a function that can compare states.
-- May look at quickCheck later
pushTestArgs :: Args
pushTestArgs = stdArgs {maxSize = 10}
intTestFunc :: String -> [Int] -> [Gene] -> State -> IO ()
intTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _int (interpretExec state)) putStrLn (name ++ " passed test.")
-- These two used for ghci testing
-- For example (in ghci): qcw prop_myTest
qcw :: (Testable a) => a -> IO ()
qcw = quickCheckWith pushTestArgs
floatTestFunc :: String -> [Float] -> [Gene] -> State -> IO ()
floatTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _float (interpretExec state)) putStrLn (name ++ " passed test.")
boolTestFunc :: String -> [Bool] -> [Gene] -> State -> IO ()
boolTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _bool (interpretExec state)) putStrLn (name ++ " passed test.")
codeTestFunc :: String -> [Gene] -> [Gene] -> State -> IO ()
codeTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _code (interpretExec state)) putStrLn (name <> " passed test.")
stringTestFunc :: String -> [String] -> [Gene] -> State -> IO ()
stringTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _string (interpretExec state)) putStrLn (name <> " passed test.")
charTestFunc :: String -> [Char] -> [Gene] -> State -> IO ()
charTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _char (interpretExec state)) putStrLn (name <> " passed test.")
vectorIntTestFunc :: String -> [[Int]] -> [Gene] -> State -> IO ()
vectorIntTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _vectorInt (interpretExec state)) putStrLn (name <> " passed test.")
vectorFloatTestFunc :: String -> [[Float]] -> [Gene] -> State -> IO ()
vectorFloatTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _vectorFloat (interpretExec state)) putStrLn (name <> " passed test.")
vcw :: (Testable a) => a -> IO ()
vcw = verboseCheckWith pushTestArgs
main :: IO ()
main = do
-- Int tests
intTestFunc "instructionIntAdd" [8] [GeneInt 6, GeneInt 2, StateFunc instructionIntAdd] emptyState
intTestFunc "instructionIntSub" [4] [GeneInt 6, GeneInt 2, StateFunc instructionIntSub] emptyState
intTestFunc "instructionIntMul" [12] [GeneInt 6, GeneInt 2, StateFunc instructionIntMul] emptyState
intTestFunc "instructionIntDiv" [3] [GeneInt 6, GeneInt 2, StateFunc instructionIntDiv] emptyState
intTestFunc "instructionIntDiv0" [0, 2] [GeneInt 2, GeneInt 0, StateFunc instructionIntDiv] emptyState
intTestFunc "instructionIntMod" [3] [GeneInt 13, GeneInt 5, StateFunc instructionIntMod] emptyState
intTestFunc "instructionIntPop" [2] [GeneInt 2, GeneInt 0, StateFunc instructionIntPop] emptyState
intTestFunc "instructionIntDup" [3, 3, 2] [GeneInt 2, GeneInt 3, StateFunc instructionIntDup] emptyState
intTestFunc "instructionIntDupN3" [2, 2, 2] [GeneInt 2, GeneInt 3, StateFunc instructionIntDupN] emptyState
intTestFunc "instructionIntDupN-1" [0] [GeneInt 0, GeneInt 2, GeneInt (-1), StateFunc instructionIntDupN] emptyState
intTestFunc "instructionIntSwap" [2, 0, 3] [GeneInt 3, GeneInt 2, GeneInt 0, StateFunc instructionIntSwap] emptyState
intTestFunc "instructionIntSwapFail" [1] [GeneInt 1, StateFunc instructionIntSwap] emptyState
intTestFunc "instructionIntRot" [1, 3, 2] [GeneInt 1, GeneInt 2, GeneInt 3, StateFunc instructionIntRot] emptyState
intTestFunc "instructionIntRotFail" [7, 8] [GeneInt 8, GeneInt 7, StateFunc instructionIntRot] emptyState
intTestFunc "instructionIntFlush" [] [GeneInt 9696, GeneInt 92, GeneInt 420, StateFunc instructionIntFlush] emptyState -- I think I'm funny
intTestFunc "instructionIntStackDepth" [2, 51, 52] [GeneInt 52, GeneInt 51, StateFunc instructionIntStackDepth] emptyState
intTestFunc "instructionIntYank" [3, 3, 2, 1] [GeneInt 3, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, StateFunc instructionIntYank] emptyState
intTestFunc "instructionIntYankDup" [3, 3, 2, 1, 3] [GeneInt 3, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, StateFunc instructionIntYankDup] emptyState
intTestFunc "instructionIntShove" [2, 3, 1, 1] [GeneInt 1, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 2, StateFunc instructionIntShove] emptyState
intTestFunc "instructionIntShoveDup" [3, 2, 3, 1, 1] [GeneInt 1, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 2, StateFunc instructionIntShoveDup] emptyState
-- Exec tests
intTestFunc "instructionExecIf" [6, 5] [GeneBool True, StateFunc instructionExecIf, Block [GeneInt 5, GeneInt 6], Block [GeneInt 7, GeneInt 8]] emptyState
intTestFunc "instructionExecDup" [8] [StateFunc instructionExecDup, GeneInt 4, StateFunc instructionIntAdd] emptyState
intTestFunc "instructionExecDoRange" [12] [GeneInt 2, Block [GeneInt 4, GeneInt 1, StateFunc instructionExecDoRange], StateFunc instructionIntAdd] emptyState
intTestFunc "instructionExecDoCount" [8] [GeneInt 2, Block [GeneInt 4, StateFunc instructionExecDoCount], StateFunc instructionIntAdd] emptyState
intTestFunc "instructionExecDoTimes" [69, 69, 69, 69, 2] [GeneInt 2, Block [GeneInt 4, StateFunc instructionExecDoTimes], GeneInt 69] emptyState
intTestFunc "instructionExecWhile" [70, 70] [GeneBool False, GeneBool True, GeneBool True, StateFunc instructionExecWhile, GeneInt 70] emptyState
intTestFunc "instructionExecDoWhile" [70, 70, 70] [GeneBool False, GeneBool True, GeneBool True, StateFunc instructionExecDoWhile, GeneInt 70] emptyState
intTestFunc "instructionExecWhenTrue" [71] [GeneBool True, StateFunc instructionExecWhen, GeneInt 71] emptyState
let loadedState = loadProgram [GeneBool False, StateFunc instructionExecWhen, GeneInt 71] emptyState
assert (emptyState == interpretExec loadedState) putStrLn "instructionExecWhenFalse passed test."
-- Float tests
floatTestFunc "instructionFloatAdd" [4.32] [GeneFloat 4.01, GeneFloat 0.31, StateFunc instructionFloatAdd] emptyState
floatTestFunc "instructionFloatSub" [3.6900003] [GeneFloat 4.01, GeneFloat 0.32, StateFunc instructionFloatSub] emptyState
floatTestFunc "instructionFloatMul" [1.38] [GeneFloat 0.12, GeneFloat 11.5, StateFunc instructionFloatMul] emptyState
floatTestFunc "instructionFloatDiv" [57.5] [GeneFloat 11.5, GeneFloat 0.2, StateFunc instructionFloatDiv] emptyState
floatTestFunc "instructionFloatDiv0" [0, 69.69] [GeneFloat 69.69, GeneFloat 0.0, StateFunc instructionFloatDiv] emptyState
floatTestFunc "instructionFloatYank" [1.1, 4.4, 3.3, 2.2] [GeneInt 3, GeneFloat 1.1, GeneFloat 2.2, GeneFloat 3.3, GeneFloat 4.4, StateFunc instructionFloatYank] emptyState
floatTestFunc "instructionFloatYankDup" [1.1, 4.4, 3.3, 2.2, 1.1] [GeneInt 3, GeneFloat 1.1, GeneFloat 2.2, GeneFloat 3.3, GeneFloat 4.4, StateFunc instructionFloatYankDup] emptyState
floatTestFunc "instructionFloatShove" [3.3, 2.2, 4.4, 1.1] [GeneInt 3, GeneFloat 1.1, GeneFloat 2.2, GeneFloat 3.3, GeneFloat 4.4, StateFunc instructionFloatShove] emptyState
floatTestFunc "instructionFloatShoveDup" [4.4, 3.3, 2.2, 4.4, 1.1] [GeneInt 3, GeneFloat 1.1, GeneFloat 2.2, GeneFloat 3.3, GeneFloat 4.4, StateFunc instructionFloatShoveDup] emptyState
floatTestFunc "instructionFloatDupNonEmpty" [4.4, 4.4, 3.3] [GeneFloat 3.3, GeneFloat 4.4, StateFunc instructionFloatDup] emptyState
floatTestFunc "instructionFloatDupEmpty" [] [StateFunc instructionFloatDup] emptyState
floatTestFunc "instructionFloatDupN3" [4.4, 4.4, 4.4, 3.3] [GeneFloat 3.3, GeneFloat 4.4, GeneInt 3, StateFunc instructionFloatDupN] emptyState
floatTestFunc "instructionFloatDupN-1" [3.3] [GeneFloat 3.3, GeneFloat 4.4, GeneInt (-1), StateFunc instructionFloatDupN] emptyState
boolTestFunc "instructionIntEqTrue" [True] [GeneInt 3, GeneInt 3, StateFunc instructionIntEq] emptyState
boolTestFunc "instructionIntEqFalse" [False] [GeneInt 3, GeneInt 5, StateFunc instructionIntEq] emptyState
boolTestFunc "instructionIntEqFail" [] [GeneInt 3, StateFunc instructionIntEq] emptyState
-- Code tests
codeTestFunc "instructionCodeFromExec" [] [StateFunc instructionCodeFromExec, StateFunc instructionFloatFromInt, StateFunc instructionCodePop] emptyState
intTestFunc "instructionCodeDoRange" [18] [GeneInt 3, GeneInt 6, StateFunc instructionCodeFromExec, StateFunc instructionIntAdd, StateFunc instructionCodeDoRange] emptyState
-- How to test instructionCodeDoThenPop?????
codeTestFunc "instructionCodeFirst" [GeneInt 5] [StateFunc instructionCodeFromExec, Block [GeneInt 5, StateFunc instructionIntSub], StateFunc instructionCodeFirst] emptyState
codeTestFunc "instructionCodeLast" [GeneBool True] [StateFunc instructionCodeFromExec, Block [GeneInt 5, StateFunc instructionIntSub, GeneBool True], StateFunc instructionCodeLast] emptyState
codeTestFunc "instructionCodeTail" [Block [GeneFloat 3.2, GeneBool True, GeneInt 3]] [StateFunc instructionCodeFromExec, Block [StateFunc instructionFloatAdd, GeneFloat 3.2, GeneBool True, GeneInt 3], StateFunc instructionCodeTail] emptyState
codeTestFunc "instructionCodeInit" [Block [GeneVectorInt [1], GeneFloat 3.2, GeneBool True]] [StateFunc instructionCodeFromExec, Block [GeneVectorInt [1], GeneFloat 3.2, GeneBool True, GeneInt 3], StateFunc instructionCodeInit] emptyState
codeTestFunc "instructionCodeWrap" [Block [GeneInt 3]] [StateFunc instructionCodeFromExec, GeneInt 3, StateFunc instructionCodeWrap] emptyState
codeTestFunc "instructionCodeList" [Block [GeneFloat 5.43, GeneInt 3]] [StateFunc instructionCodeFromExec, GeneInt 3, StateFunc instructionCodeFromExec, GeneFloat 5.43, StateFunc instructionCodeList] emptyState
codeTestFunc "instructionCodeCombine2Blocks" [Block [GeneInt 3, GeneInt 4, GeneInt 1, GeneInt 2]] [StateFunc instructionCodeFromExec, Block [GeneInt 1, GeneInt 2], StateFunc instructionCodeFromExec, Block [GeneInt 3, GeneInt 4], StateFunc instructionCodeCombine] emptyState
codeTestFunc "instructionCodeCombine1Block1Single" [Block [GeneInt 3, GeneInt 4, GeneInt 1]] [StateFunc instructionCodeFromExec, GeneInt 1, StateFunc instructionCodeFromExec, Block [GeneInt 3, GeneInt 4], StateFunc instructionCodeCombine] emptyState
codeTestFunc "instructionCodeCombine1Single1Block" [Block [GeneInt 3, GeneInt 1, GeneInt 2]] [StateFunc instructionCodeFromExec, Block [GeneInt 1, GeneInt 2], StateFunc instructionCodeFromExec, GeneInt 3, StateFunc instructionCodeCombine] emptyState
codeTestFunc "instrucitonCodeCombine2Single" [Block [GeneInt 2, GeneInt 1]] [StateFunc instructionCodeFromExec, GeneInt 1, StateFunc instructionCodeFromExec, GeneInt 2, StateFunc instructionCodeCombine] emptyState
intTestFunc "instructionCodeDo" [3] [StateFunc instructionCodeFromExec, GeneInt 3, StateFunc instructionCodeDo] emptyState
-- How to test instructionCodeDoDup??? We would would need a multi stack testing function
boolTestFunc "instructionCodeIsCodeBlockTrue" [True] [StateFunc instructionCodeFromExec, Block [GeneInt 0], StateFunc instructionCodeIsCodeBlock] emptyState
boolTestFunc "instructionCodeIsCodeBlockFalse" [False] [StateFunc instructionCodeFromExec, GeneInt 0, StateFunc instructionCodeIsCodeBlock] emptyState
boolTestFunc "instructionCodeIsSingularTrue" [True] [StateFunc instructionCodeFromExec, GeneInt 0, StateFunc instructionCodeIsSingular] emptyState
boolTestFunc "instructionCodeIsSingularFalse" [False] [StateFunc instructionCodeFromExec, Block [GeneInt 0], StateFunc instructionCodeIsSingular] emptyState
intTestFunc "instructionCodeDoCount" [15] [GeneInt 6, StateFunc instructionCodeFromExec, StateFunc instructionIntAdd, StateFunc instructionCodeDoCount] emptyState
intTestFunc "instructionCodeDoTimes" [13] [GeneInt 6, GeneInt 3, GeneInt 4, GeneInt 2, StateFunc instructionCodeFromExec, StateFunc instructionIntAdd, StateFunc instructionCodeDoTimes] emptyState
intTestFunc "instructionCodeIfTrue" [6] [GeneBool True, StateFunc instructionCodeFromExec, GeneInt 3, StateFunc instructionCodeFromExec, GeneInt 6, StateFunc instructionCodeIf] emptyState
intTestFunc "instructionCodeIfFalse" [3] [GeneBool False, StateFunc instructionCodeFromExec, GeneInt 3, StateFunc instructionCodeFromExec, GeneInt 6, StateFunc instructionCodeIf] emptyState
intTestFunc "instructionCodeWhen" [6, 3, 6] [GeneInt 6, GeneInt 3, GeneInt 4, GeneInt 2, GeneBool True, StateFunc instructionCodeFromExec, StateFunc instructionIntAdd, StateFunc instructionCodeWhen] emptyState
boolTestFunc "instructionCodeMemberTrue" [True] [StateFunc instructionCodeFromExec, GeneInt 2, StateFunc instructionCodeFromExec, Block [GeneFloat 3.6, GeneInt 2, GeneVectorInt [8, 9]], StateFunc instructionCodeMember] emptyState
boolTestFunc "instructionCodeMemberFalse" [False] [StateFunc instructionCodeFromExec, GeneInt 7, StateFunc instructionCodeFromExec, Block [GeneFloat 3.6, GeneInt 2, GeneVectorInt [8, 9]], StateFunc instructionCodeMember] emptyState
boolTestFunc "instructionCodeMember2Blocks" [False] [StateFunc instructionCodeFromExec, Block [GeneInt 7, GeneInt 0], StateFunc instructionCodeFromExec, Block [GeneFloat 3.6, GeneInt 2, GeneVectorInt [8, 9]], StateFunc instructionCodeMember] emptyState
codeTestFunc "instructionCodeNInBounds" [GeneInt 0] [StateFunc instructionCodeFromExec, Block [GeneInt 0, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, GeneInt 5], GeneInt 0, StateFunc instructionCodeN] emptyState
codeTestFunc "instructionCodeNInBoundsEnd" [GeneInt 5] [StateFunc instructionCodeFromExec, Block [GeneInt 0, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, GeneInt 5], GeneInt 5, StateFunc instructionCodeN] emptyState
codeTestFunc "instructionCodeNModded" [GeneInt 3] [StateFunc instructionCodeFromExec, Block [GeneInt 0, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, GeneInt 5], GeneInt 9, StateFunc instructionCodeN] emptyState
codeTestFunc "instructionMakeEmptyCodeBlock" [Block []] [StateFunc instructionMakeEmptyCodeBlock] emptyState
boolTestFunc "instructionIsEmptyCodeBlockTrue" [True] [StateFunc instructionCodeFromExec, Block [], StateFunc instructionIsEmptyCodeBlock] emptyState
intTestFunc "instructionCodeSize" [8] [StateFunc instructionCodeFromExec, Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6], StateFunc instructionCodeSize] emptyState
codeTestFunc "instructionCodeExtractInBounds" [GeneInt 3] [StateFunc instructionCodeFromExec, Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6], GeneInt 3, StateFunc instructionCodeExtract] emptyState
codeTestFunc "instructionCodeExtractOutBounds" [GeneInt 3] [StateFunc instructionCodeFromExec, Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6], GeneInt 11, StateFunc instructionCodeExtract] emptyState
codeTestFunc "instructionCodeExtractLastEmptyBlock" [Block []] [StateFunc instructionCodeFromExec, Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], Block []], GeneInt 7, StateFunc instructionCodeExtract] emptyState
codeTestFunc "instructionCodeExtractBlock" [Block [GeneInt 2, GeneInt 3]] [StateFunc instructionCodeFromExec, Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], Block []], GeneInt 1, StateFunc instructionCodeExtract] emptyState
codeTestFunc "instructionCodeExtractEdgeCase" [Block []] [StateFunc instructionCodeFromExec, Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], Block []], GeneInt 7, StateFunc instructionCodeExtract] emptyState
codeTestFunc "instructionCodeExtractNotBlock" [GeneInt 2] [StateFunc instructionCodeFromExec, GeneInt 2, GeneInt 56, StateFunc instructionCodeExtract] emptyState
codeTestFunc
"instructionCodeInsertInBounds"
[Block [GeneInt 1, Block [GeneInt 2, GeneInt 9999, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6, Block [GeneInt 7, GeneInt 8], GeneInt 9]]
[StateFunc instructionCodeFromExec, GeneInt 9999, StateFunc instructionCodeFromExec, Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6, Block [GeneInt 7, GeneInt 8], GeneInt 9], GeneInt 3, StateFunc instructionCodeInsert]
emptyState
codeTestFunc
"instructionCodeInsertOutBounds"
[Block [GeneInt 1, Block [GeneInt 2, GeneInt 9999, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6, Block [GeneInt 7, GeneInt 8], GeneInt 9]]
[StateFunc instructionCodeFromExec, GeneInt 9999, StateFunc instructionCodeFromExec, Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6, Block [GeneInt 7, GeneInt 8], GeneInt 9], GeneInt 15, StateFunc instructionCodeInsert]
emptyState
codeTestFunc "instructionCodeInsertNotBlock" [Block [GeneInt 2, GeneInt 1]] [StateFunc instructionCodeFromExec, GeneInt 2, StateFunc instructionCodeFromExec, GeneInt 1, GeneInt 1, StateFunc instructionCodeInsert] emptyState
intTestFunc "instructionCodePosition0" [0] [StateFunc instructionCodeFromExec, GeneInt 1, StateFunc instructionCodeFromExec, Block [GeneInt 1, GeneInt 2, GeneInt 3], StateFunc instructionCodeFirstPosition] emptyState
intTestFunc "instructionCodePosition-1" [-1] [StateFunc instructionCodeFromExec, GeneInt 7, StateFunc instructionCodeFromExec, Block [GeneInt 1, GeneInt 2, GeneInt 3], StateFunc instructionCodeFirstPosition] emptyState
intTestFunc "instructionCodePositionEmptyBlock" [0] [StateFunc instructionCodeFromExec, Block [], StateFunc instructionCodeFromExec, Block [], StateFunc instructionCodeFirstPosition] emptyState
codeTestFunc "instructionCodePositionBadStack" [GeneInt 1] [StateFunc instructionCodeFromExec, GeneInt 1, StateFunc instructionCodeFirstPosition] emptyState -- tests to ensure base case of insufficient code stack works. Should do this on more of these instructions.
codeTestFunc "instructionCodeReverse2Args" [Block [GeneInt 2, GeneInt 1]] [StateFunc instructionCodeFromExec, Block [GeneInt 1, GeneInt 2], StateFunc instructionCodeReverse] emptyState
codeTestFunc "instructionCodeReverse3Args" [Block [GeneInt 3, GeneInt 2, GeneInt 1]] [StateFunc instructionCodeFromExec, Block [GeneInt 1, GeneInt 2, GeneInt 3], StateFunc instructionCodeReverse] emptyState
codeTestFunc "instructionCodeReverseNonBlock" [GeneInt 1] [StateFunc instructionCodeFromExec, GeneInt 1, StateFunc instructionCodeReverse] emptyState
-- String tests
stringTestFunc "instructionStringConcat" ["123abc"] [GeneString "abc", GeneString "123", StateFunc instructionStringConcat] emptyState
stringTestFunc "instructionStringSwap" ["abc", "123"] [GeneString "abc", GeneString "123", StateFunc instructionStringSwap] emptyState
stringTestFunc "instructionStringInsertString" ["123INSabc"] [GeneString "abc", GeneString "123", StateFunc instructionStringConcat, GeneString "INS", StateFunc instructionStringSwap, GeneInt 3, StateFunc instructionStringInsertString] emptyState
stringTestFunc "instructionStringFromFirstChar" ["1"] [GeneString "123", StateFunc instructionStringFromFirstChar] emptyState
stringTestFunc "instructionStringFromNthChar" ["a"] [GeneString "123abc", GeneInt 3, StateFunc instructionStringFromNthChar] emptyState
intTestFunc "instructionStringIndexOfString3" [3] [GeneString "a", GeneString "123abc", StateFunc instructionStringIndexOfString] emptyState
intTestFunc "instructionStringIndexOfString-1" [-1] [GeneString "z", GeneString "123abc", StateFunc instructionStringIndexOfString] emptyState
boolTestFunc "instructionStringContainsStringTrue" [True] [GeneString "a", GeneString "123abc", StateFunc instructionStringContainsString] emptyState
boolTestFunc "instructionStringContainsStringFalse" [False] [GeneString "z", GeneString "123abc", StateFunc instructionStringContainsString] emptyState
stringTestFunc "instructionStringSplitOnStringMult" ["nd", "r fri", "llo gam", "h"] [GeneString "e", GeneString "hello gamer friend", StateFunc instructionStringSplitOnString] emptyState
stringTestFunc "instructionStringSplitOnStringEmpty" ["", "hello gamer frien"] [GeneString "d", GeneString "hello gamer friend", StateFunc instructionStringSplitOnString] emptyState
stringTestFunc "instructionStringReplaceFirstStringSuccess" ["thREPLACEs is a sentence"] [GeneString "REPLACE", GeneString "i", GeneString "this is a sentence", StateFunc instructionStringReplaceFirstString] emptyState
stringTestFunc "instructionStringReplaceFirstStringFail" ["this is a sentence"] [GeneString "REPLACE", GeneString "z", GeneString "this is a sentence", StateFunc instructionStringReplaceFirstString] emptyState
stringTestFunc "instructionStringReplaceNStringSuccess" ["thREPLACEs REPLACEs a sentence i"] [GeneString "REPLACE", GeneString "i", GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringReplaceNString] emptyState
stringTestFunc "instructionStringReplaceNStringFail" ["this is a sentence i"] [GeneString "REPLACE", GeneString "z", GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringReplaceNString] emptyState
stringTestFunc "instructionStringReplaceAllStringSuccess" ["thREPLACEs REPLACEs a sentence REPLACE"] [GeneString "REPLACE", GeneString "i", GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringReplaceAllString] emptyState
stringTestFunc "instructionStringReplaceAllStringFail" ["this is a sentence i"] [GeneString "REPLACE", GeneString "z", GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringReplaceAllString] emptyState
stringTestFunc "instructionStringRemoveFirstStringSuccess" ["ths is a sentence"] [GeneString "i", GeneString "this is a sentence", StateFunc instructionStringRemoveFirstString] emptyState
stringTestFunc "instructionStringRemoveFirstStringFail" ["this is a sentence"] [GeneString "z", GeneString "this is a sentence", StateFunc instructionStringRemoveFirstString] emptyState
stringTestFunc "instructionStringRemoveNStringSuccess" ["ths s a sentence i"] [GeneString "i", GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringRemoveNString] emptyState
stringTestFunc "instructionStringRemoveNStringFail" ["this is a sentence i"] [GeneString "z", GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringRemoveNString] emptyState
stringTestFunc "instructionStringRemoveAllStringSuccess" ["ths s a sentence "] [GeneString "i", GeneString "this is a sentence i", StateFunc instructionStringRemoveAllString] emptyState
stringTestFunc "instructionStringRemoveAllStringFail" ["this is a sentence i"] [GeneString "z", GeneString "this is a sentence i", StateFunc instructionStringRemoveAllString] emptyState
intTestFunc "instructionStringOccurrencesOfString3" [3] [GeneString "i", GeneString "this is a sentence i", StateFunc instructionStringOccurrencesOfString] emptyState
intTestFunc "instructionStringOccurrencesOfString3" [2] [GeneString "is", GeneString "this is a sentence i", StateFunc instructionStringOccurrencesOfString] emptyState
intTestFunc "instructionStringOccurrencesOfString0" [0] [GeneString "z", GeneString "this is a sentence i", StateFunc instructionStringOccurrencesOfString] emptyState
stringTestFunc "instructionStringInsertChar" ["123Zabc"] [GeneString "abc", GeneString "123", StateFunc instructionStringConcat, GeneChar 'Z', GeneInt 3, StateFunc instructionStringInsertChar] emptyState
boolTestFunc "instructionStringContainsCharTrue" [True] [GeneString "abc", GeneChar 'a', StateFunc instructionStringContainsChar] emptyState
boolTestFunc "instructionStringContainsCharFalse" [False] [GeneString "abc", GeneChar 'z', StateFunc instructionStringContainsChar] emptyState
intTestFunc "instructionStringIndexOfChar3" [3] [GeneChar 'a', GeneString "123abc", StateFunc instructionStringIndexOfChar] emptyState
intTestFunc "instructionStringIndexOfChar-1" [-1] [GeneChar 'z', GeneString "123abc", StateFunc instructionStringIndexOfChar] emptyState
stringTestFunc "instructionStringSplitOnCharMult" ["nd", "r fri", "llo gam", "h"] [GeneChar 'e', GeneString "hello gamer friend", StateFunc instructionStringSplitOnChar] emptyState
stringTestFunc "instructionStringSplitOnCharEmpty" ["", "hello gamer frien"] [GeneChar 'd', GeneString "hello gamer friend", StateFunc instructionStringSplitOnChar] emptyState
stringTestFunc "instructionStringReplaceFirstCharSuccess" ["thRs is a sentence"] [GeneChar 'R', GeneChar 'i', GeneString "this is a sentence", StateFunc instructionStringReplaceFirstChar] emptyState
stringTestFunc "instructionStringReplaceFirstCharFail" ["this is a sentence"] [GeneChar 'R', GeneChar 'z', GeneString "this is a sentence", StateFunc instructionStringReplaceFirstChar] emptyState
stringTestFunc "instructionStringReplaceNCharSuccess" ["thRs Rs a sentence i"] [GeneChar 'R', GeneChar 'i', GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringReplaceNChar] emptyState
stringTestFunc "instructionStringReplaceNCharFail" ["this is a sentence i"] [GeneChar 'R', GeneChar 'z', GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringReplaceNChar] emptyState
stringTestFunc "instructionStringReplaceAllCharSuccess" ["thRs Rs a sentence R"] [GeneChar 'R', GeneChar 'i', GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringReplaceAllChar] emptyState
stringTestFunc "instructionStringReplaceAllCharFail" ["this is a sentence i"] [GeneChar 'R', GeneChar 'z', GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringReplaceAllChar] emptyState
stringTestFunc "instructionStringRemoveFirstCharSuccess" ["ths is a sentence"] [GeneChar 'i', GeneString "this is a sentence", StateFunc instructionStringRemoveFirstChar] emptyState
stringTestFunc "instructionStringRemoveFirstCharFail" ["this is a sentence"] [GeneChar 'z', GeneString "this is a sentence", StateFunc instructionStringRemoveFirstChar] emptyState
stringTestFunc "instructionStringRemoveNCharSuccess" ["ths s a sentence i"] [GeneChar 'i', GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringRemoveNChar] emptyState
stringTestFunc "instructionStringRemoveNCharFail" ["this is a sentence i"] [GeneChar 'z', GeneString "this is a sentence i", GeneInt 2, StateFunc instructionStringRemoveNChar] emptyState
stringTestFunc "instructionStringRemoveAllCharSuccess" ["ths s a sentence "] [GeneChar 'i', GeneString "this is a sentence i", StateFunc instructionStringRemoveAllChar] emptyState
stringTestFunc "instructionStringRemoveAllCharFail" ["this is a sentence i"] [GeneChar 'z', GeneString "this is a sentence i", StateFunc instructionStringRemoveAllChar] emptyState
intTestFunc "instructionStringOccurrencesOfChar3" [3] [GeneChar 'i', GeneString "this is a sentence i", StateFunc instructionStringOccurrencesOfChar] emptyState
intTestFunc "instructionStringOccurrencesOfChar0" [0] [GeneChar 'z', GeneString "this is a sentence i", StateFunc instructionStringOccurrencesOfChar] emptyState
stringTestFunc "instructionStringReverse" ["321cba"] [GeneString "abc123", StateFunc instructionStringReverse] emptyState
stringTestFunc "instructionStringHead3" ["abc"] [GeneString "abc123", GeneInt 3, StateFunc instructionStringHead] emptyState
stringTestFunc "instructionStringHead0" [""] [GeneString "abc123", GeneInt 0, StateFunc instructionStringHead] emptyState
stringTestFunc "instructionStringTail3" ["123"] [GeneString "abc123", GeneInt 3, StateFunc instructionStringTail] emptyState
stringTestFunc "instructionStringTail0" [""] [GeneString "abc123", GeneInt 0, StateFunc instructionStringTail] emptyState
stringTestFunc "instructionStringAppendChar" ["Rabc123"] [GeneString "abc123", GeneChar 'R', StateFunc instructionStringAppendChar] emptyState
stringTestFunc "instructionStringRestFull" ["bc123"] [GeneString "abc123", StateFunc instructionStringRest] emptyState
stringTestFunc "instructionStringRestEmpty" [""] [GeneString "", StateFunc instructionStringRest] emptyState
stringTestFunc "instructionStringButLastFull" ["abc12"] [GeneString "abc123", StateFunc instructionStringButLast] emptyState
stringTestFunc "instructionStringButLastEmpty" [""] [GeneString "", StateFunc instructionStringButLast] emptyState
stringTestFunc "instructionStringDrop3" ["123"] [GeneString "abc123", GeneInt 3, StateFunc instructionStringDrop] emptyState
stringTestFunc "instructionStringDrop0" ["abc123"] [GeneString "abc123", GeneInt 0, StateFunc instructionStringDrop] emptyState
stringTestFunc "instructionStringButLastN3" ["abc"] [GeneString "abc123", GeneInt 3, StateFunc instructionStringButLastN] emptyState
stringTestFunc "instructionStringButLastN0" ["abc123"] [GeneString "abc123", GeneInt 0, StateFunc instructionStringButLastN] emptyState
intTestFunc "instructionStringLength6" [6] [GeneString "abc123", StateFunc instructionStringLength] emptyState
stringTestFunc "instructionStringMakeEmpty" ["", "abc123"] [GeneString "abc123", StateFunc instructionStringMakeEmpty] emptyState
stringTestFunc "instructionStringRemoveNth" ["abc23"] [GeneString "abc123", GeneInt 3, StateFunc instructionStringRemoveNth] emptyState
stringTestFunc "instructionStringSetNth" ["abR123"] [GeneString "abc123", GeneInt 2, GeneChar 'R', StateFunc instructionStringSetNth] emptyState
stringTestFunc "instructionStringStripWhitespace" ["abc123"] [GeneString " \r \n abc123 \t", StateFunc instructionStringStripWhitespace] emptyState
stringTestFunc "instructionStringFromBoolTrue" ["True"] [GeneBool True, StateFunc instructionStringFromBool] emptyState
stringTestFunc "instructionStringFromBoolTrue" ["False"] [GeneBool False, StateFunc instructionStringFromBool] emptyState
stringTestFunc "instructionStringFromInt1000" ["1000"] [GeneInt 1000, StateFunc instructionStringFromInt] emptyState
stringTestFunc "instructionStringFromInt-1" ["-1"] [GeneInt (-1), StateFunc instructionStringFromInt] emptyState
stringTestFunc "instructionStringFromFloat3.2" ["3.2"] [GeneFloat 3.2, StateFunc instructionStringFromFloat] emptyState
stringTestFunc "instructionStringFromFloat-99.0" ["-99.0"] [GeneFloat (-99.0), StateFunc instructionStringFromFloat] emptyState
stringTestFunc "instructionStringFromChar" ["Z"] [GeneChar 'Z', StateFunc instructionStringFromChar] emptyState
stringTestFunc "instructionStringFromChar" [" "] [GeneChar ' ', StateFunc instructionStringFromChar] emptyState
-- char instructions
stringTestFunc "instructionCharConcat" ["ab"] [GeneChar 'b', GeneChar 'a', StateFunc instructionCharConcat] emptyState
charTestFunc "instructionCharFromFirstCharSuccess" ['a'] [GeneString "abc123", StateFunc instructionCharFromFirstChar] emptyState
charTestFunc "instructionCharFromFirstCharFail" [] [GeneString "", StateFunc instructionCharFromFirstChar] emptyState
charTestFunc "instructionCharFromLastCharSuccess" ['3'] [GeneString "abc123", StateFunc instructionCharFromLastChar] emptyState
charTestFunc "instructionCharFromLastCharFail" [] [GeneString "", StateFunc instructionCharFromLastChar] emptyState
charTestFunc "instructionCharFromNthCharSuccess" ['c'] [GeneString "abc123", GeneInt 2, StateFunc instructionCharFromNthChar] emptyState
boolTestFunc "instructionCharIsWhitespaceSpace" [True] [GeneChar ' ', StateFunc instructionCharIsWhitespace] emptyState
boolTestFunc "instructionCharIsWhitespacet" [True] [GeneChar '\t', StateFunc instructionCharIsWhitespace] emptyState
boolTestFunc "instructionCharIsWhitespacer" [True] [GeneChar '\r', StateFunc instructionCharIsWhitespace] emptyState
boolTestFunc "instructionCharIsWhitespacen" [True] [GeneChar '\n', StateFunc instructionCharIsWhitespace] emptyState
boolTestFunc "instructionCharIsWhitespaceFalse" [False] [GeneChar 'a', StateFunc instructionCharIsWhitespace] emptyState
boolTestFunc "instructionCharIsLetterTrue" [True] [GeneChar 'a', StateFunc instructionCharIsLetter] emptyState
boolTestFunc "instructionCharIsLetterFalse" [False] [GeneChar '1', StateFunc instructionCharIsLetter] emptyState
boolTestFunc "instructionCharIsDigitTrue" [True] [GeneChar '1', StateFunc instructionCharIsDigit] emptyState
boolTestFunc "instructionCharIsDigitFalse" [False] [GeneChar 'a', StateFunc instructionCharIsDigit] emptyState
-- vector int instructions
vectorIntTestFunc "instructionVectorIntConcat" [[4, 5, 6, 1, 2, 3]] [GeneVectorInt [1, 2, 3], GeneVectorInt [4, 5, 6], StateFunc instructionVectorIntConcat] emptyState
vectorIntTestFunc "instructionVectorIntConj" [[99, 1, 2, 3]] [GeneVectorInt [1, 2, 3], GeneInt 99, StateFunc instructionVectorIntConj] emptyState
vectorIntTestFunc "instructionIntTakeN" [[1, 2], [6, 7, 8]] [GeneVectorInt [6, 7, 8], GeneVectorInt [1, 2, 3], GeneInt 2, StateFunc instructionVectorIntTakeN] emptyState
vectorIntTestFunc "instructionVectorIntSubVector" [[1, 2, 3]] [GeneVectorInt [0, 1, 2, 3, 4, 5], GeneInt 3, GeneInt 1, StateFunc instructionVectorIntSubVector] emptyState
intTestFunc "instructionVectorIntFirst" [1] [GeneVectorInt [1,2,3,4,5], StateFunc instructionVectorIntFirst] emptyState
intTestFunc "instructionVectorIntLast" [5] [GeneVectorInt [1,2,3,4,5], StateFunc instructionVectorIntLast] emptyState
intTestFunc "instructionVectorIntNthInBounds" [2] [GeneVectorInt [1,2,3,4,5], GeneInt 1, StateFunc instructionVectorIntNth] emptyState
intTestFunc "instructionVectorIntNthOverflow" [2] [GeneVectorInt [1,2,3,4,5], GeneInt 6, StateFunc instructionVectorIntNth] emptyState
vectorIntTestFunc "instructionVectorIntRestFull" [[2,3,4,5]] [GeneVectorInt [1,2,3,4,5], StateFunc instructionVectorIntRest] emptyState
vectorIntTestFunc "instructionVectorIntRestEmpty" [[]] [GeneVectorInt [], StateFunc instructionVectorIntRest] emptyState
vectorIntTestFunc "instructionVectorIntButLastFull" [[1,2,3,4]] [GeneVectorInt [1,2,3,4,5], StateFunc instructionVectorIntButLast] emptyState
vectorIntTestFunc "instructionVectorIntButLastEmpty" [[]] [GeneVectorInt [], StateFunc instructionVectorIntButLast] emptyState
intTestFunc "instructionVectorIntLength3" [3] [GeneVectorInt [1,2,3], StateFunc instructionVectorIntLength] emptyState
intTestFunc "instructionVectorIntLength0" [0] [GeneVectorInt [], StateFunc instructionVectorIntLength] emptyState
vectorIntTestFunc "instructionVectorIntReverse" [[4,3,2,1]] [GeneVectorInt [1,2,3,4], StateFunc instructionVectorIntReverse] emptyState
intTestFunc "instructionVectorIntPushAllFull" [1,2,3,4,99] [GeneVectorInt [1,2,3,4], GeneInt 99, StateFunc instructionVectorIntPushAll] emptyState
intTestFunc "instructionVectorIntPushAllEmpty" [99] [GeneVectorInt [], GeneInt 99, StateFunc instructionVectorIntPushAll] emptyState
vectorIntTestFunc "instructionVectorIntMakeEmpty" [[]] [StateFunc instructionVectorIntMakeEmpty] emptyState
boolTestFunc "instructionVectorIntIsEmptyTrue" [True] [GeneVectorInt [], StateFunc instructionVectorIntIsEmpty] emptyState
boolTestFunc "instructionVectorIntIsEmptyFalse" [False] [GeneVectorInt [1,2,3,4], StateFunc instructionVectorIntIsEmpty] emptyState
intTestFunc "instructionVectorIntIndexOf1" [1] [GeneVectorInt [1,2,3,4,5], GeneInt 2, StateFunc instructionVectorIntIndexOf] emptyState
intTestFunc "instructionVectorIntIndexOfFail" [-1] [GeneVectorInt [], GeneInt 2, StateFunc instructionVectorIntIndexOf] emptyState
intTestFunc "instructionVectorIntOccurrencesOf2" [2] [GeneVectorInt [1,2,3,4,2,6,7], GeneInt 2, StateFunc instructionVectorIntOccurrencesOf] emptyState
intTestFunc "instructionVectorIntOccurrencesOf0" [0] [GeneVectorInt [1,2,3,4,2,6,7], GeneInt 0, StateFunc instructionVectorIntOccurrencesOf] emptyState
vectorIntTestFunc "instructionVectorIntSetNth3" [[0,1,2,99,4,5]] [GeneVectorInt [0,1,2,3,4,5], GeneInt 99, GeneInt 3, StateFunc instructionVectorIntSetNth] emptyState
vectorIntTestFunc "instructionVectorIntSetNth9" [[0,1,2,99,4,5]] [GeneVectorInt [0,1,2,3,4,5], GeneInt 99, GeneInt 9, StateFunc instructionVectorIntSetNth] emptyState
vectorIntTestFunc "instructionVectorIntReplace3" [[0,1,2,99,4,5,99,5,99]] [GeneInt 99, GeneInt 3, GeneVectorInt [0,1,2,3,4,5,3,5,3], StateFunc instructionVectorIntReplace] emptyState
vectorIntTestFunc "instructionVectorIntReplace-1" [[0,1,2,3,4,5,3,5,3]] [GeneInt 99, GeneInt (-1), GeneVectorInt [0,1,2,3,4,5,3,5,3], StateFunc instructionVectorIntReplace] emptyState
vectorIntTestFunc "instructionVectorIntReplaceFirst3" [[0,1,2,99,4,5,3,5,3]] [GeneInt 99, GeneInt 3, GeneVectorInt [0,1,2,3,4,5,3,5,3], StateFunc instructionVectorIntReplaceFirst] emptyState
vectorIntTestFunc "instructionVectorIntReplaceFirst-2" [[0,1,2,3,4,5,3,5,3]] [GeneInt 99, GeneInt (-2), GeneVectorInt [0,1,2,3,4,5,3,5,3], StateFunc instructionVectorIntReplaceFirst] emptyState
vectorIntTestFunc "instructionVectorIntRemove" [[0,1,2,4,5,5]] [GeneInt 3, GeneVectorInt [0,1,2,3,4,5,3,5,3], StateFunc instructionVectorIntRemove] emptyState
intTestFunc "instructionVectorIntIterate" [66] [GeneInt 40, GeneVectorInt [0,1,2,3,4,5,3,5,3], StateFunc instructionVectorIntIterate, StateFunc instructionIntAdd] emptyState
-- vector float functions
vectorFloatTestFunc "instructionVectorFloatConcat" [[4.0, 5.0, 6.0, 1.0, 2.0, 3.0]] [GeneVectorFloat [1.0, 2.0, 3.0], GeneVectorFloat [4.0, 5.0, 6.0], StateFunc instructionVectorFloatConcat] emptyState
vectorFloatTestFunc "instructionVectorFloatConj" [[99.0, 1.0, 2.0, 3.0]] [GeneVectorFloat [1.0, 2.0, 3.0], GeneFloat 99.0, StateFunc instructionVectorFloatConj] emptyState
vectorFloatTestFunc "instructionFloatTakeN" [[1.0, 2.0], [6.0, 7.0, 8.0]] [GeneVectorFloat [6.0, 7.0, 8.0], GeneVectorFloat [1.0, 2.0, 3.0], GeneInt 2, StateFunc instructionVectorFloatTakeN] emptyState
vectorFloatTestFunc "instructionVectorFloatSubVector" [[1.0, 2.0, 3.0]] [GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], GeneInt 3, GeneInt 1, StateFunc instructionVectorFloatSubVector] emptyState
floatTestFunc "instructionVectorFloatFirst" [1.0] [GeneVectorFloat [1.0,2.0,3.0,4.0,5.0], StateFunc instructionVectorFloatFirst] emptyState
floatTestFunc "instructionVectorFloatLast" [5.0] [GeneVectorFloat [1.0,2.0,3.0,4.0,5.0], StateFunc instructionVectorFloatLast] emptyState
floatTestFunc "instructionVectorFloatNthInBounds" [2.0] [GeneVectorFloat [1.0,2.0,3.0,4.0,5.0], GeneInt 1, StateFunc instructionVectorFloatNth] emptyState
floatTestFunc "instructionVectorFloatNthOverflow" [2.0] [GeneVectorFloat [1.0,2.0,3.0,4.0,5.0], GeneInt 6, StateFunc instructionVectorFloatNth] emptyState
vectorFloatTestFunc "instructionVectorFloatRestFull" [[2.0,3.0,4.0,5.0]] [GeneVectorFloat [1.0,2.0,3.0,4.0,5.0], StateFunc instructionVectorFloatRest] emptyState
vectorFloatTestFunc "instructionVectorFloatRestEmpty" [[]] [GeneVectorFloat [], StateFunc instructionVectorFloatRest] emptyState
vectorFloatTestFunc "instructionVectorFloatButLastFull" [[1.0,2.0,3.0,4.0]] [GeneVectorFloat [1.0,2.0,3.0,4.0,5.0], StateFunc instructionVectorFloatButLast] emptyState
vectorFloatTestFunc "instructionVectorFloatButLastEmpty" [[]] [GeneVectorFloat [], StateFunc instructionVectorFloatButLast] emptyState
intTestFunc "instructionVectorFloatLength3" [3] [GeneVectorFloat [1.0,2.0,3.0], StateFunc instructionVectorFloatLength] emptyState
intTestFunc "instructionVectorFloatLength0" [0] [GeneVectorFloat [], StateFunc instructionVectorFloatLength] emptyState
vectorFloatTestFunc "instructionVectorFloatReverse" [[4.0,3.0,2.0,1.0]] [GeneVectorFloat [1.0,2.0,3.0,4.0], StateFunc instructionVectorFloatReverse] emptyState
floatTestFunc "instructionVectorFloatPushAllFull" [1.0,2.0,3.0,4.0,99.0] [GeneVectorFloat [1.0,2.0,3.0,4.0], GeneFloat 99.0, StateFunc instructionVectorFloatPushAll] emptyState
floatTestFunc "instructionVectorFloatPushAllEmpty" [99.0] [GeneVectorFloat [], GeneFloat 99.0, StateFunc instructionVectorFloatPushAll] emptyState
vectorFloatTestFunc "instructionVectorFloatMakeEmpty" [[]] [StateFunc instructionVectorFloatMakeEmpty] emptyState
boolTestFunc "instructionVectorFloatIsEmptyTrue" [True] [GeneVectorFloat [], StateFunc instructionVectorFloatIsEmpty] emptyState
boolTestFunc "instructionVectorFloatIsEmptyFalse" [False] [GeneVectorFloat [1.0,2.0,3.0,4.0], StateFunc instructionVectorFloatIsEmpty] emptyState
intTestFunc "instructionVectorFloatIndexOf1" [1] [GeneVectorFloat [1.0,2.0,3.0,4.0,5.0], GeneFloat 2.0, StateFunc instructionVectorFloatIndexOf] emptyState
intTestFunc "instructionVectorFloatIndexOfFail" [-1] [GeneVectorFloat [], GeneFloat 2.0, StateFunc instructionVectorFloatIndexOf] emptyState
intTestFunc "instructionVectorFloatOccurrencesOf2" [2] [GeneVectorFloat [1.0,2.0,3.0,4.0,2.0,6.0,7.0], GeneFloat 2.0, StateFunc instructionVectorFloatOccurrencesOf] emptyState
intTestFunc "instructionVectorFloatOccurrencesOf0" [0] [GeneVectorFloat [1.0,2.0,3.0,4.0,2.0,6.0,7.0], GeneFloat 0.0, StateFunc instructionVectorFloatOccurrencesOf] emptyState
vectorFloatTestFunc "instructionVectorFloatSetNth3" [[0.0,1.0,2.0,99.0,4.0,5.0]] [GeneVectorFloat [0.0,1.0,2.0,3.0,4.0,5.0], GeneFloat 99.0, GeneInt 3, StateFunc instructionVectorFloatSetNth] emptyState
vectorFloatTestFunc "instructionVectorFloatSetNth9" [[0.0,1.0,2.0,99.0,4.0,5.0]] [GeneVectorFloat [0.0,1.0,2.0,3.0,4.0,5.0], GeneFloat 99.0, GeneInt 9, StateFunc instructionVectorFloatSetNth] emptyState
vectorFloatTestFunc "instructionVectorFloatReplace3" [[0.0,1.0,2.0,99.0,4.0,5.0,99.0,5.0,99.0]] [GeneFloat 99.0, GeneFloat 3.0, GeneVectorFloat [0.0,1.0,2.0,3.0,4.0,5.0,3.0,5.0,3.0], StateFunc instructionVectorFloatReplace] emptyState
vectorFloatTestFunc "instructionVectorFloatReplace-1" [[0.0,1.0,2.0,3.0,4.0,5.0,3.0,5.0,3.0]] [GeneFloat 99.0, GeneFloat (-1.0), GeneVectorFloat [0.0,1.0,2.0,3.0,4.0,5.0,3.0,5.0,3.0], StateFunc instructionVectorFloatReplace] emptyState
vectorFloatTestFunc "instructionVectorFloatReplaceFirst3" [[0.0,1.0,2.0,99.0,4.0,5.0,3.0,5.0,3.0]] [GeneFloat 99.0, GeneFloat 3.0, GeneVectorFloat [0.0,1.0,2.0,3.0,4.0,5.0,3.0,5.0,3.0], StateFunc instructionVectorFloatReplaceFirst] emptyState
vectorFloatTestFunc "instructionVectorFloatReplaceFirst-2" [[0.0,1.0,2.0,3.0,4.0,5.0,3.0,5.0,3.0]] [GeneFloat 99.0, GeneFloat (-2.0), GeneVectorFloat [0.0,1.0,2.0,3.0,4.0,5.0,3.0,5.0,3.0], StateFunc instructionVectorFloatReplaceFirst] emptyState
vectorFloatTestFunc "instructionVectorFloatRemove" [[0.0,1.0,2.0,4.0,5.0,5.0]] [GeneFloat 3, GeneVectorFloat [0.0,1.0,2.0,3.0,4.0,5.0,3.0,5.0,3.0], StateFunc instructionVectorFloatRemove] emptyState
floatTestFunc "instructionVectorFloatIterate" [66.0] [GeneFloat 40.0, GeneVectorFloat [0.0,1.0,2.0,3.0,4.0,5.0,3.0,5.0,3.0], StateFunc instructionVectorFloatIterate, StateFunc instructionFloatAdd] emptyState
qcw prop_IntAdd
qcw prop_IntSub
qcw prop_IntMul
qcw prop_IntDiv
qcw prop_IntMod
qcw prop_IntFromFloat
qcw prop_IntFromBool
qcw prop_IntMin
qcw prop_IntMax
qcw prop_IntInc
qcw prop_IntDec
qcw prop_IntLT
qcw prop_IntGT
qcw prop_IntLTE
qcw prop_IntGTE
qcw prop_IntDup
qcw prop_IntPop

324
test/MainOld.hs Normal file
View File

@ -0,0 +1,324 @@
import Control.Exception (assert)
import Instructions
import Push
import State
-- import Debug.Trace
-- TODO: Need a function that can compare states.
-- May look at quickCheck later
intTestFunc :: String -> [Int] -> [Gene] -> State -> IO ()
intTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _int (interpretExec state)) putStrLn (name ++ " passed test.")
floatTestFunc :: String -> [Float] -> [Gene] -> State -> IO ()
floatTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _float (interpretExec state)) putStrLn (name ++ " passed test.")
boolTestFunc :: String -> [Bool] -> [Gene] -> State -> IO ()
boolTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _bool (interpretExec state)) putStrLn (name ++ " passed test.")
codeTestFunc :: String -> [Gene] -> [Gene] -> State -> IO ()
codeTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _code (interpretExec state)) putStrLn (name <> " passed test.")
stringTestFunc :: String -> [String] -> [Gene] -> State -> IO ()
stringTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _string (interpretExec state)) putStrLn (name <> " passed test.")
charTestFunc :: String -> [Char] -> [Gene] -> State -> IO ()
charTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _char (interpretExec state)) putStrLn (name <> " passed test.")
vectorIntTestFunc :: String -> [[Int]] -> [Gene] -> State -> IO ()
vectorIntTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _vectorInt (interpretExec state)) putStrLn (name <> " passed test.")
vectorFloatTestFunc :: String -> [[Float]] -> [Gene] -> State -> IO ()
vectorFloatTestFunc name goal genome startState =
let state = loadProgram genome startState
in assert (goal == _vectorFloat (interpretExec state)) putStrLn (name <> " passed test.")
main :: IO ()
main = do
-- Int tests
intTestFunc "instructionIntAdd" [8] [GeneInt 6, GeneInt 2, StateFunc (instructionIntAdd, "placeholder")] emptyState
intTestFunc "instructionIntSub" [4] [GeneInt 6, GeneInt 2, StateFunc (instructionIntSub, "placeholder")] emptyState
intTestFunc "instructionIntMul" [12] [GeneInt 6, GeneInt 2, StateFunc (instructionIntMul, "placeholder")] emptyState
intTestFunc "instructionIntDiv" [3] [GeneInt 6, GeneInt 2, StateFunc (instructionIntDiv, "placeholder")] emptyState
intTestFunc "instructionIntDiv0" [0, 2] [GeneInt 2, GeneInt 0, StateFunc (instructionIntDiv, "placeholder")] emptyState
intTestFunc "instructionIntMod" [3] [GeneInt 13, GeneInt 5, StateFunc (instructionIntMod, "placeholder")] emptyState
intTestFunc "instructionIntPop" [2] [GeneInt 2, GeneInt 0, StateFunc (instructionIntPop, "placeholder")] emptyState
intTestFunc "instructionIntDup" [3, 3, 2] [GeneInt 2, GeneInt 3, StateFunc (instructionIntDup, "placeholder")] emptyState
intTestFunc "instructionIntDupN3" [2, 2, 2] [GeneInt 2, GeneInt 3, StateFunc (instructionIntDupN, "placeholder")] emptyState
intTestFunc "instructionIntDupN-1" [0] [GeneInt 0, GeneInt 2, GeneInt (-1), StateFunc (instructionIntDupN, "placeholder")] emptyState
intTestFunc "instructionIntSwap" [2, 0, 3] [GeneInt 3, GeneInt 2, GeneInt 0, StateFunc (instructionIntSwap, "placeholder")] emptyState
intTestFunc "instructionIntSwapFail" [1] [GeneInt 1, StateFunc (instructionIntSwap, "placeholder")] emptyState
intTestFunc "instructionIntRot" [1, 3, 2] [GeneInt 1, GeneInt 2, GeneInt 3, StateFunc (instructionIntRot, "placeholder")] emptyState
intTestFunc "instructionIntRotFail" [7, 8] [GeneInt 8, GeneInt 7, StateFunc (instructionIntRot, "placeholder")] emptyState
intTestFunc "instructionIntFlush" [] [GeneInt 9696, GeneInt 92, GeneInt 420, StateFunc (instructionIntFlush, "placeholder")] emptyState -- I think I'm funny
intTestFunc "instructionIntStackDepth" [2, 51, 52] [GeneInt 52, GeneInt 51, StateFunc (instructionIntStackDepth, "placeholder")] emptyState
intTestFunc "instructionIntYank" [3, 3, 2, 1] [GeneInt 3, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, StateFunc (instructionIntYank, "placeholder")] emptyState
intTestFunc "instructionIntYankDup" [3, 3, 2, 1, 3] [GeneInt 3, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, StateFunc (instructionIntYankDup, "placeholder")] emptyState
intTestFunc "instructionIntShove" [2, 3, 1, 1] [GeneInt 1, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 2, StateFunc (instructionIntShove, "placeholder")] emptyState
intTestFunc "instructionIntShoveDup" [3, 2, 3, 1, 1] [GeneInt 1, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 2, StateFunc (instructionIntShoveDup, "placeholder")] emptyState
-- Exec tests
intTestFunc "instructionExecIf" [6, 5] [GeneBool True, StateFunc (instructionExecIf, "placeholder"), Block [GeneInt 5, GeneInt 6], Block [GeneInt 7, GeneInt 8]] emptyState
intTestFunc "instructionExecDup" [8] [StateFunc (instructionExecDup, "placeholder"), GeneInt 4, StateFunc (instructionIntAdd, "placeholder")] emptyState
intTestFunc "instructionExecDoRange" [12] [GeneInt 2, Block [GeneInt 4, GeneInt 1, StateFunc (instructionExecDoRange, "placeholder")], StateFunc (instructionIntAdd, "placeholder")] emptyState
intTestFunc "instructionExecDoCount" [8] [GeneInt 2, Block [GeneInt 4, StateFunc (instructionExecDoCount, "placeholder")], StateFunc (instructionIntAdd, "placeholder")] emptyState
intTestFunc "instructionExecDoTimes" [69, 69, 69, 69, 2] [GeneInt 2, Block [GeneInt 4, StateFunc (instructionExecDoTimes, "placeholder")], GeneInt 69] emptyState
intTestFunc "instructionExecWhile" [70, 70] [GeneBool False, GeneBool True, GeneBool True, StateFunc (instructionExecWhile, "placeholder"), GeneInt 70] emptyState
intTestFunc "instructionExecDoWhile" [70, 70, 70] [GeneBool False, GeneBool True, GeneBool True, StateFunc (instructionExecDoWhile, "placeholder"), GeneInt 70] emptyState
intTestFunc "instructionExecWhenTrue" [71] [GeneBool True, StateFunc (instructionExecWhen, "placeholder"), GeneInt 71] emptyState
let loadedState = loadProgram [GeneBool False, StateFunc (instructionExecWhen, "placeholder"), GeneInt 71] emptyState
assert (emptyState == interpretExec loadedState) putStrLn "instructionExecWhenFalse passed test."
-- Float tests
floatTestFunc "instructionFloatAdd" [4.32] [GeneFloat 4.01, GeneFloat 0.31, StateFunc (instructionFloatAdd, "placeholder")] emptyState
floatTestFunc "instructionFloatSub" [3.6900003] [GeneFloat 4.01, GeneFloat 0.32, StateFunc (instructionFloatSub, "placeholder")] emptyState
floatTestFunc "instructionFloatMul" [1.38] [GeneFloat 0.12, GeneFloat 11.5, StateFunc (instructionFloatMul, "placeholder")] emptyState
floatTestFunc "instructionFloatDiv" [57.5] [GeneFloat 11.5, GeneFloat 0.2, StateFunc (instructionFloatDiv, "placeholder")] emptyState
floatTestFunc "instructionFloatDiv0" [0, 69.69] [GeneFloat 69.69, GeneFloat 0.0, StateFunc (instructionFloatDiv, "placeholder")] emptyState
floatTestFunc "instructionFloatYank" [1.1, 4.4, 3.3, 2.2] [GeneInt 3, GeneFloat 1.1, GeneFloat 2.2, GeneFloat 3.3, GeneFloat 4.4, StateFunc (instructionFloatYank, "placeholder")] emptyState
floatTestFunc "instructionFloatYankDup" [1.1, 4.4, 3.3, 2.2, 1.1] [GeneInt 3, GeneFloat 1.1, GeneFloat 2.2, GeneFloat 3.3, GeneFloat 4.4, StateFunc (instructionFloatYankDup, "placeholder")] emptyState
floatTestFunc "instructionFloatShove" [3.3, 2.2, 4.4, 1.1] [GeneInt 3, GeneFloat 1.1, GeneFloat 2.2, GeneFloat 3.3, GeneFloat 4.4, StateFunc (instructionFloatShove, "placeholder")] emptyState
floatTestFunc "instructionFloatShoveDup" [4.4, 3.3, 2.2, 4.4, 1.1] [GeneInt 3, GeneFloat 1.1, GeneFloat 2.2, GeneFloat 3.3, GeneFloat 4.4, StateFunc (instructionFloatShoveDup, "placeholder")] emptyState
floatTestFunc "instructionFloatDupNonEmpty" [4.4, 4.4, 3.3] [GeneFloat 3.3, GeneFloat 4.4, StateFunc (instructionFloatDup, "placeholder")] emptyState
floatTestFunc "instructionFloatDupEmpty" [] [StateFunc (instructionFloatDup, "placeholder")] emptyState
floatTestFunc "instructionFloatDupN3" [4.4, 4.4, 4.4, 3.3] [GeneFloat 3.3, GeneFloat 4.4, GeneInt 3, StateFunc (instructionFloatDupN, "placeholder")] emptyState
floatTestFunc "instructionFloatDupN-1" [3.3] [GeneFloat 3.3, GeneFloat 4.4, GeneInt (-1), StateFunc (instructionFloatDupN, "placeholder")] emptyState
boolTestFunc "instructionIntEqTrue" [True] [GeneInt 3, GeneInt 3, StateFunc (instructionIntEq, "placeholder")] emptyState
boolTestFunc "instructionIntEqFalse" [False] [GeneInt 3, GeneInt 5, StateFunc (instructionIntEq, "placeholder")] emptyState
boolTestFunc "instructionIntEqFail" [] [GeneInt 3, StateFunc (instructionIntEq, "placeholder")] emptyState
-- Code tests
codeTestFunc "instructionCodeFromExec" [] [StateFunc (instructionCodeFromExec, "placeholder"), StateFunc (instructionFloatFromInt, "placeholder"), StateFunc (instructionCodePop, "placeholder")] emptyState
intTestFunc "instructionCodeDoRange" [18] [GeneInt 3, GeneInt 6, StateFunc (instructionCodeFromExec, "placeholder"), StateFunc (instructionIntAdd, "placeholder"), StateFunc (instructionCodeDoRange, "placeholder")] emptyState
-- How to test instructionCodeDoThenPop?????
codeTestFunc "instructionCodeFirst" [GeneInt 5] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 5, StateFunc (instructionIntSub, "placeholder")], StateFunc (instructionCodeFirst, "placeholder")] emptyState
codeTestFunc "instructionCodeLast" [GeneBool True] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 5, StateFunc (instructionIntSub, "placeholder"), GeneBool True], StateFunc (instructionCodeLast, "placeholder")] emptyState
codeTestFunc "instructionCodeTail" [Block [GeneFloat 3.2, GeneBool True, GeneInt 3]] [StateFunc (instructionCodeFromExec, "placeholder"), Block [StateFunc (instructionFloatAdd, "placeholder"), GeneFloat 3.2, GeneBool True, GeneInt 3], StateFunc (instructionCodeTail, "placeholder")] emptyState
codeTestFunc "instructionCodeInit" [Block [GeneVectorInt [1], GeneFloat 3.2, GeneBool True]] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneVectorInt [1], GeneFloat 3.2, GeneBool True, GeneInt 3], StateFunc (instructionCodeInit, "placeholder")] emptyState
codeTestFunc "instructionCodeWrap" [Block [GeneInt 3]] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 3, StateFunc (instructionCodeWrap, "placeholder")] emptyState
codeTestFunc "instructionCodeList" [Block [GeneFloat 5.43, GeneInt 3]] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 3, StateFunc (instructionCodeFromExec, "placeholder"), GeneFloat 5.43, StateFunc (instructionCodeList, "placeholder")] emptyState
codeTestFunc "instructionCodeCombine2Blocks" [Block [GeneInt 3, GeneInt 4, GeneInt 1, GeneInt 2]] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, GeneInt 2], StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 3, GeneInt 4], StateFunc (instructionCodeCombine, "placeholder")] emptyState
codeTestFunc "instructionCodeCombine1Block1Single" [Block [GeneInt 3, GeneInt 4, GeneInt 1]] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 1, StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 3, GeneInt 4], StateFunc (instructionCodeCombine, "placeholder")] emptyState
codeTestFunc "instructionCodeCombine1Single1Block" [Block [GeneInt 3, GeneInt 1, GeneInt 2]] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, GeneInt 2], StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 3, StateFunc (instructionCodeCombine, "placeholder")] emptyState
codeTestFunc "instrucitonCodeCombine2Single" [Block [GeneInt 2, GeneInt 1]] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 1, StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 2, StateFunc (instructionCodeCombine, "placeholder")] emptyState
intTestFunc "instructionCodeDo" [3] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 3, StateFunc (instructionCodeDo, "placeholder")] emptyState
-- How to test instructionCodeDoDup??? We would would need a multi stack testing function
boolTestFunc "instructionCodeIsCodeBlockTrue" [True] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 0], StateFunc (instructionCodeIsCodeBlock, "placeholder")] emptyState
boolTestFunc "instructionCodeIsCodeBlockFalse" [False] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 0, StateFunc (instructionCodeIsCodeBlock, "placeholder")] emptyState
boolTestFunc "instructionCodeIsSingularTrue" [True] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 0, StateFunc (instructionCodeIsSingular, "placeholder")] emptyState
boolTestFunc "instructionCodeIsSingularFalse" [False] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 0], StateFunc (instructionCodeIsSingular, "placeholder")] emptyState
intTestFunc "instructionCodeDoCount" [15] [GeneInt 6, StateFunc (instructionCodeFromExec, "placeholder"), StateFunc (instructionIntAdd, "placeholder"), StateFunc (instructionCodeDoCount, "placeholder")] emptyState
intTestFunc "instructionCodeDoTimes" [13] [GeneInt 6, GeneInt 3, GeneInt 4, GeneInt 2, StateFunc (instructionCodeFromExec, "placeholder"), StateFunc (instructionIntAdd, "placeholder"), StateFunc (instructionCodeDoTimes, "placeholder")] emptyState
intTestFunc "instructionCodeIfTrue" [6] [GeneBool True, StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 3, StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 6, StateFunc (instructionCodeIf, "placeholder")] emptyState
intTestFunc "instructionCodeIfFalse" [3] [GeneBool False, StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 3, StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 6, StateFunc (instructionCodeIf, "placeholder")] emptyState
intTestFunc "instructionCodeWhen" [6, 3, 6] [GeneInt 6, GeneInt 3, GeneInt 4, GeneInt 2, GeneBool True, StateFunc (instructionCodeFromExec, "placeholder"), StateFunc (instructionIntAdd, "placeholder"), StateFunc (instructionCodeWhen, "placeholder")] emptyState
boolTestFunc "instructionCodeMemberTrue" [True] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 2, StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneFloat 3.6, GeneInt 2, GeneVectorInt [8, 9]], StateFunc (instructionCodeMember, "placeholder")] emptyState
boolTestFunc "instructionCodeMemberFalse" [False] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 7, StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneFloat 3.6, GeneInt 2, GeneVectorInt [8, 9]], StateFunc (instructionCodeMember, "placeholder")] emptyState
boolTestFunc "instructionCodeMember2Blocks" [False] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 7, GeneInt 0], StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneFloat 3.6, GeneInt 2, GeneVectorInt [8, 9]], StateFunc (instructionCodeMember, "placeholder")] emptyState
codeTestFunc "instructionCodeNInBounds" [GeneInt 0] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 0, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, GeneInt 5], GeneInt 0, StateFunc (instructionCodeN, "placeholder")] emptyState
codeTestFunc "instructionCodeNInBoundsEnd" [GeneInt 5] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 0, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, GeneInt 5], GeneInt 5, StateFunc (instructionCodeN, "placeholder")] emptyState
codeTestFunc "instructionCodeNModded" [GeneInt 3] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 0, GeneInt 1, GeneInt 2, GeneInt 3, GeneInt 4, GeneInt 5], GeneInt 9, StateFunc (instructionCodeN, "placeholder")] emptyState
codeTestFunc "instructionMakeEmptyCodeBlock" [Block []] [StateFunc (instructionMakeEmptyCodeBlock, "placeholder")] emptyState
boolTestFunc "instructionIsEmptyCodeBlockTrue" [True] [StateFunc (instructionCodeFromExec, "placeholder"), Block [], StateFunc (instructionIsEmptyCodeBlock, "placeholder")] emptyState
intTestFunc "instructionCodeSize" [8] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6], StateFunc (instructionCodeSize, "placeholder")] emptyState
codeTestFunc "instructionCodeExtractInBounds" [GeneInt 3] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6], GeneInt 3, StateFunc (instructionCodeExtract, "placeholder")] emptyState
codeTestFunc "instructionCodeExtractOutBounds" [GeneInt 3] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6], GeneInt 11, StateFunc (instructionCodeExtract, "placeholder")] emptyState
codeTestFunc "instructionCodeExtractLastEmptyBlock" [Block []] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], Block []], GeneInt 7, StateFunc (instructionCodeExtract, "placeholder")] emptyState
codeTestFunc "instructionCodeExtractBlock" [Block [GeneInt 2, GeneInt 3]] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], Block []], GeneInt 1, StateFunc (instructionCodeExtract, "placeholder")] emptyState
codeTestFunc "instructionCodeExtractEdgeCase" [Block []] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], Block []], GeneInt 7, StateFunc (instructionCodeExtract, "placeholder")] emptyState
codeTestFunc "instructionCodeExtractNotBlock" [GeneInt 2] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 2, GeneInt 56, StateFunc (instructionCodeExtract, "placeholder")] emptyState
codeTestFunc
"instructionCodeInsertInBounds"
[Block [GeneInt 1, Block [GeneInt 2, GeneInt 9999, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6, Block [GeneInt 7, GeneInt 8], GeneInt 9]]
[StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 9999, StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6, Block [GeneInt 7, GeneInt 8], GeneInt 9], GeneInt 3, StateFunc (instructionCodeInsert, "placeholder")]
emptyState
codeTestFunc
"instructionCodeInsertOutBounds"
[Block [GeneInt 1, Block [GeneInt 2, GeneInt 9999, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6, Block [GeneInt 7, GeneInt 8], GeneInt 9]]
[StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 9999, StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, Block [GeneInt 2, GeneInt 3], Block [GeneInt 4, GeneInt 5], GeneInt 6, Block [GeneInt 7, GeneInt 8], GeneInt 9], GeneInt 15, StateFunc (instructionCodeInsert, "placeholder")]
emptyState
codeTestFunc "instructionCodeInsertNotBlock" [Block [GeneInt 2, GeneInt 1]] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 2, StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 1, GeneInt 1, StateFunc (instructionCodeInsert, "placeholder")] emptyState
intTestFunc "instructionCodePosition0" [0] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 1, StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, GeneInt 2, GeneInt 3], StateFunc (instructionCodeFirstPosition, "placeholder")] emptyState
intTestFunc "instructionCodePosition-1" [-1] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 7, StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, GeneInt 2, GeneInt 3], StateFunc (instructionCodeFirstPosition, "placeholder")] emptyState
intTestFunc "instructionCodePositionEmptyBlock" [0] [StateFunc (instructionCodeFromExec, "placeholder"), Block [], StateFunc (instructionCodeFromExec, "placeholder"), Block [], StateFunc (instructionCodeFirstPosition, "placeholder")] emptyState
codeTestFunc "instructionCodePositionBadStack" [GeneInt 1] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 1, StateFunc (instructionCodeFirstPosition, "placeholder")] emptyState -- tests to ensure base case of insufficient code stack works. Should do this on more of these instructions.
codeTestFunc "instructionCodeReverse2Args" [Block [GeneInt 2, GeneInt 1]] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, GeneInt 2], StateFunc (instructionCodeReverse, "placeholder")] emptyState
codeTestFunc "instructionCodeReverse3Args" [Block [GeneInt 3, GeneInt 2, GeneInt 1]] [StateFunc (instructionCodeFromExec, "placeholder"), Block [GeneInt 1, GeneInt 2, GeneInt 3], StateFunc (instructionCodeReverse, "placeholder")] emptyState
codeTestFunc "instructionCodeReverseNonBlock" [GeneInt 1] [StateFunc (instructionCodeFromExec, "placeholder"), GeneInt 1, StateFunc (instructionCodeReverse, "placeholder")] emptyState
-- String tests
stringTestFunc "instructionStringConcat" ["123abc"] [GeneString "abc", GeneString "123", StateFunc (instructionStringConcat, "placeholder")] emptyState
stringTestFunc "instructionStringSwap" ["abc", "123"] [GeneString "abc", GeneString "123", StateFunc (instructionStringSwap, "placeholder")] emptyState
stringTestFunc "instructionStringInsertString" ["123INSabc"] [GeneString "abc", GeneString "123", StateFunc (instructionStringConcat, "placeholder"), GeneString "INS", StateFunc (instructionStringSwap, "placeholder"), GeneInt 3, StateFunc (instructionStringInsertString, "placeholder")] emptyState
stringTestFunc "instructionStringFromFirstChar" ["1"] [GeneString "123", StateFunc (instructionStringFromFirstChar, "placeholder")] emptyState
stringTestFunc "instructionStringFromNthChar" ["a"] [GeneString "123abc", GeneInt 3, StateFunc (instructionStringFromNthChar, "placeholder")] emptyState
intTestFunc "instructionStringIndexOfString3" [3] [GeneString "a", GeneString "123abc", StateFunc (instructionStringIndexOfString, "placeholder")] emptyState
intTestFunc "instructionStringIndexOfString-1" [-1] [GeneString "z", GeneString "123abc", StateFunc (instructionStringIndexOfString, "placeholder")] emptyState
boolTestFunc "instructionStringContainsStringTrue" [True] [GeneString "a", GeneString "123abc", StateFunc (instructionStringContainsString, "placeholder")] emptyState
boolTestFunc "instructionStringContainsStringFalse" [False] [GeneString "z", GeneString "123abc", StateFunc (instructionStringContainsString, "placeholder")] emptyState
stringTestFunc "instructionStringSplitOnStringMult" ["nd", "r fri", "llo gam", "h"] [GeneString "e", GeneString "hello gamer friend", StateFunc (instructionStringSplitOnString, "placeholder")] emptyState
stringTestFunc "instructionStringSplitOnStringEmpty" ["", "hello gamer frien"] [GeneString "d", GeneString "hello gamer friend", StateFunc (instructionStringSplitOnString, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceFirstStringSuccess" ["thREPLACEs is a sentence"] [GeneString "REPLACE", GeneString "i", GeneString "this is a sentence", StateFunc (instructionStringReplaceFirstString, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceFirstStringFail" ["this is a sentence"] [GeneString "REPLACE", GeneString "z", GeneString "this is a sentence", StateFunc (instructionStringReplaceFirstString, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceNStringSuccess" ["thREPLACEs REPLACEs a sentence i"] [GeneString "REPLACE", GeneString "i", GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringReplaceNString, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceNStringFail" ["this is a sentence i"] [GeneString "REPLACE", GeneString "z", GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringReplaceNString, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceAllStringSuccess" ["thREPLACEs REPLACEs a sentence REPLACE"] [GeneString "REPLACE", GeneString "i", GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringReplaceAllString, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceAllStringFail" ["this is a sentence i"] [GeneString "REPLACE", GeneString "z", GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringReplaceAllString, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveFirstStringSuccess" ["ths is a sentence"] [GeneString "i", GeneString "this is a sentence", StateFunc (instructionStringRemoveFirstString, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveFirstStringFail" ["this is a sentence"] [GeneString "z", GeneString "this is a sentence", StateFunc (instructionStringRemoveFirstString, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveNStringSuccess" ["ths s a sentence i"] [GeneString "i", GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringRemoveNString, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveNStringFail" ["this is a sentence i"] [GeneString "z", GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringRemoveNString, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveAllStringSuccess" ["ths s a sentence "] [GeneString "i", GeneString "this is a sentence i", StateFunc (instructionStringRemoveAllString, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveAllStringFail" ["this is a sentence i"] [GeneString "z", GeneString "this is a sentence i", StateFunc (instructionStringRemoveAllString, "placeholder")] emptyState
intTestFunc "instructionStringOccurrencesOfString3" [3] [GeneString "i", GeneString "this is a sentence i", StateFunc (instructionStringOccurrencesOfString, "placeholder")] emptyState
intTestFunc "instructionStringOccurrencesOfString3" [2] [GeneString "is", GeneString "this is a sentence i", StateFunc (instructionStringOccurrencesOfString, "placeholder")] emptyState
intTestFunc "instructionStringOccurrencesOfString0" [0] [GeneString "z", GeneString "this is a sentence i", StateFunc (instructionStringOccurrencesOfString, "placeholder")] emptyState
stringTestFunc "instructionStringInsertChar" ["123Zabc"] [GeneString "abc", GeneString "123", StateFunc (instructionStringConcat, "placeholder"), GeneChar 'Z', GeneInt 3, StateFunc (instructionStringInsertChar, "placeholder")] emptyState
boolTestFunc "instructionStringContainsCharTrue" [True] [GeneString "abc", GeneChar 'a', StateFunc (instructionStringContainsChar, "placeholder")] emptyState
boolTestFunc "instructionStringContainsCharFalse" [False] [GeneString "abc", GeneChar 'z', StateFunc (instructionStringContainsChar, "placeholder")] emptyState
intTestFunc "instructionStringIndexOfChar3" [3] [GeneChar 'a', GeneString "123abc", StateFunc (instructionStringIndexOfChar, "placeholder")] emptyState
intTestFunc "instructionStringIndexOfChar-1" [-1] [GeneChar 'z', GeneString "123abc", StateFunc (instructionStringIndexOfChar, "placeholder")] emptyState
stringTestFunc "instructionStringSplitOnCharMult" ["nd", "r fri", "llo gam", "h"] [GeneChar 'e', GeneString "hello gamer friend", StateFunc (instructionStringSplitOnChar, "placeholder")] emptyState
stringTestFunc "instructionStringSplitOnCharEmpty" ["", "hello gamer frien"] [GeneChar 'd', GeneString "hello gamer friend", StateFunc (instructionStringSplitOnChar, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceFirstCharSuccess" ["thRs is a sentence"] [GeneChar 'R', GeneChar 'i', GeneString "this is a sentence", StateFunc (instructionStringReplaceFirstChar, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceFirstCharFail" ["this is a sentence"] [GeneChar 'R', GeneChar 'z', GeneString "this is a sentence", StateFunc (instructionStringReplaceFirstChar, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceNCharSuccess" ["thRs Rs a sentence i"] [GeneChar 'R', GeneChar 'i', GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringReplaceNChar, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceNCharFail" ["this is a sentence i"] [GeneChar 'R', GeneChar 'z', GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringReplaceNChar, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceAllCharSuccess" ["thRs Rs a sentence R"] [GeneChar 'R', GeneChar 'i', GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringReplaceAllChar, "placeholder")] emptyState
stringTestFunc "instructionStringReplaceAllCharFail" ["this is a sentence i"] [GeneChar 'R', GeneChar 'z', GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringReplaceAllChar, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveFirstCharSuccess" ["ths is a sentence"] [GeneChar 'i', GeneString "this is a sentence", StateFunc (instructionStringRemoveFirstChar, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveFirstCharFail" ["this is a sentence"] [GeneChar 'z', GeneString "this is a sentence", StateFunc (instructionStringRemoveFirstChar, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveNCharSuccess" ["ths s a sentence i"] [GeneChar 'i', GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringRemoveNChar, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveNCharFail" ["this is a sentence i"] [GeneChar 'z', GeneString "this is a sentence i", GeneInt 2, StateFunc (instructionStringRemoveNChar, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveAllCharSuccess" ["ths s a sentence "] [GeneChar 'i', GeneString "this is a sentence i", StateFunc (instructionStringRemoveAllChar, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveAllCharFail" ["this is a sentence i"] [GeneChar 'z', GeneString "this is a sentence i", StateFunc (instructionStringRemoveAllChar, "placeholder")] emptyState
intTestFunc "instructionStringOccurrencesOfChar3" [3] [GeneChar 'i', GeneString "this is a sentence i", StateFunc (instructionStringOccurrencesOfChar, "placeholder")] emptyState
intTestFunc "instructionStringOccurrencesOfChar0" [0] [GeneChar 'z', GeneString "this is a sentence i", StateFunc (instructionStringOccurrencesOfChar, "placeholder")] emptyState
stringTestFunc "instructionStringReverse" ["321cba"] [GeneString "abc123", StateFunc (instructionStringReverse, "placeholder")] emptyState
stringTestFunc "instructionStringHead3" ["abc"] [GeneString "abc123", GeneInt 3, StateFunc (instructionStringHead, "placeholder")] emptyState
stringTestFunc "instructionStringHead0" [""] [GeneString "abc123", GeneInt 0, StateFunc (instructionStringHead, "placeholder")] emptyState
stringTestFunc "instructionStringTail3" ["123"] [GeneString "abc123", GeneInt 3, StateFunc (instructionStringTail, "placeholder")] emptyState
stringTestFunc "instructionStringTail0" [""] [GeneString "abc123", GeneInt 0, StateFunc (instructionStringTail, "placeholder")] emptyState
stringTestFunc "instructionStringAppendChar" ["Rabc123"] [GeneString "abc123", GeneChar 'R', StateFunc (instructionStringAppendChar, "placeholder")] emptyState
stringTestFunc "instructionStringRestFull" ["bc123"] [GeneString "abc123", StateFunc (instructionStringRest, "placeholder")] emptyState
stringTestFunc "instructionStringRestEmpty" [""] [GeneString "", StateFunc (instructionStringRest, "placeholder")] emptyState
stringTestFunc "instructionStringButLastFull" ["abc12"] [GeneString "abc123", StateFunc (instructionStringButLast, "placeholder")] emptyState
stringTestFunc "instructionStringButLastEmpty" [""] [GeneString "", StateFunc (instructionStringButLast, "placeholder")] emptyState
stringTestFunc "instructionStringDrop3" ["123"] [GeneString "abc123", GeneInt 3, StateFunc (instructionStringDrop, "placeholder")] emptyState
stringTestFunc "instructionStringDrop0" ["abc123"] [GeneString "abc123", GeneInt 0, StateFunc (instructionStringDrop, "placeholder")] emptyState
stringTestFunc "instructionStringButLastN3" ["abc"] [GeneString "abc123", GeneInt 3, StateFunc (instructionStringButLastN, "placeholder")] emptyState
stringTestFunc "instructionStringButLastN0" ["abc123"] [GeneString "abc123", GeneInt 0, StateFunc (instructionStringButLastN, "placeholder")] emptyState
intTestFunc "instructionStringLength6" [6] [GeneString "abc123", StateFunc (instructionStringLength, "placeholder")] emptyState
stringTestFunc "instructionStringMakeEmpty" ["", "abc123"] [GeneString "abc123", StateFunc (instructionStringMakeEmpty, "placeholder")] emptyState
stringTestFunc "instructionStringRemoveNth" ["abc23"] [GeneString "abc123", GeneInt 3, StateFunc (instructionStringRemoveNth, "placeholder")] emptyState
stringTestFunc "instructionStringSetNth" ["abR123"] [GeneString "abc123", GeneInt 2, GeneChar 'R', StateFunc (instructionStringSetNth, "placeholder")] emptyState
stringTestFunc "instructionStringStripWhitespace" ["abc123"] [GeneString " \r \n abc123 \t", StateFunc (instructionStringStripWhitespace, "placeholder")] emptyState
stringTestFunc "instructionStringFromBoolTrue" ["True"] [GeneBool True, StateFunc (instructionStringFromBool, "placeholder")] emptyState
stringTestFunc "instructionStringFromBoolTrue" ["False"] [GeneBool False, StateFunc (instructionStringFromBool, "placeholder")] emptyState
stringTestFunc "instructionStringFromInt1000" ["1000"] [GeneInt 1000, StateFunc (instructionStringFromInt, "placeholder")] emptyState
stringTestFunc "instructionStringFromInt-1" ["-1"] [GeneInt (-1), StateFunc (instructionStringFromInt, "placeholder")] emptyState
stringTestFunc "instructionStringFromFloat3.2" ["3.2"] [GeneFloat 3.2, StateFunc (instructionStringFromFloat, "placeholder")] emptyState
stringTestFunc "instructionStringFromFloat-99.0" ["-99.0"] [GeneFloat (-99.0), StateFunc (instructionStringFromFloat, "placeholder")] emptyState
stringTestFunc "instructionStringFromChar" ["Z"] [GeneChar 'Z', StateFunc (instructionStringFromChar, "placeholder")] emptyState
stringTestFunc "instructionStringFromChar" [" "] [GeneChar ' ', StateFunc (instructionStringFromChar, "placeholder")] emptyState
-- char instructions
stringTestFunc "instructionCharConcat" ["ab"] [GeneChar 'b', GeneChar 'a', StateFunc (instructionCharConcat, "placeholder")] emptyState
charTestFunc "instructionCharFromFirstCharSuccess" ['a'] [GeneString "abc123", StateFunc (instructionCharFromFirstChar, "placeholder")] emptyState
charTestFunc "instructionCharFromFirstCharFail" [] [GeneString "", StateFunc (instructionCharFromFirstChar, "placeholder")] emptyState
charTestFunc "instructionCharFromLastCharSuccess" ['3'] [GeneString "abc123", StateFunc (instructionCharFromLastChar, "placeholder")] emptyState
charTestFunc "instructionCharFromLastCharFail" [] [GeneString "", StateFunc (instructionCharFromLastChar, "placeholder")] emptyState
charTestFunc "instructionCharFromNthCharSuccess" ['c'] [GeneString "abc123", GeneInt 2, StateFunc (instructionCharFromNthChar, "placeholder")] emptyState
boolTestFunc "instructionCharIsWhitespaceSpace" [True] [GeneChar ' ', StateFunc (instructionCharIsWhitespace, "placeholder")] emptyState
boolTestFunc "instructionCharIsWhitespacet" [True] [GeneChar '\t', StateFunc (instructionCharIsWhitespace, "placeholder")] emptyState
boolTestFunc "instructionCharIsWhitespacer" [True] [GeneChar '\r', StateFunc (instructionCharIsWhitespace, "placeholder")] emptyState
boolTestFunc "instructionCharIsWhitespacen" [True] [GeneChar '\n', StateFunc (instructionCharIsWhitespace, "placeholder")] emptyState
boolTestFunc "instructionCharIsWhitespaceFalse" [False] [GeneChar 'a', StateFunc (instructionCharIsWhitespace, "placeholder")] emptyState
boolTestFunc "instructionCharIsLetterTrue" [True] [GeneChar 'a', StateFunc (instructionCharIsLetter, "placeholder")] emptyState
boolTestFunc "instructionCharIsLetterFalse" [False] [GeneChar '1', StateFunc (instructionCharIsLetter, "placeholder")] emptyState
boolTestFunc "instructionCharIsDigitTrue" [True] [GeneChar '1', StateFunc (instructionCharIsDigit, "placeholder")] emptyState
boolTestFunc "instructionCharIsDigitFalse" [False] [GeneChar 'a', StateFunc (instructionCharIsDigit, "placeholder")] emptyState
-- vector int instructions
vectorIntTestFunc "instructionVectorIntConcat" [[4, 5, 6, 1, 2, 3]] [GeneVectorInt [1, 2, 3], GeneVectorInt [4, 5, 6], StateFunc (instructionVectorIntConcat, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntConj" [[99, 1, 2, 3]] [GeneVectorInt [1, 2, 3], GeneInt 99, StateFunc (instructionVectorIntConj, "placeholder")] emptyState
vectorIntTestFunc "instructionIntTakeN" [[1, 2], [6, 7, 8]] [GeneVectorInt [6, 7, 8], GeneVectorInt [1, 2, 3], GeneInt 2, StateFunc (instructionVectorIntTakeN, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntSubVector" [[1, 2, 3]] [GeneVectorInt [0, 1, 2, 3, 4, 5], GeneInt 3, GeneInt 1, StateFunc (instructionVectorIntSubVector, "placeholder")] emptyState
intTestFunc "instructionVectorIntFirst" [1] [GeneVectorInt [1, 2, 3, 4, 5], StateFunc (instructionVectorIntFirst, "placeholder")] emptyState
intTestFunc "instructionVectorIntLast" [5] [GeneVectorInt [1, 2, 3, 4, 5], StateFunc (instructionVectorIntLast, "placeholder")] emptyState
intTestFunc "instructionVectorIntNthInBounds" [2] [GeneVectorInt [1, 2, 3, 4, 5], GeneInt 1, StateFunc (instructionVectorIntNth, "placeholder")] emptyState
intTestFunc "instructionVectorIntNthOverflow" [2] [GeneVectorInt [1, 2, 3, 4, 5], GeneInt 6, StateFunc (instructionVectorIntNth, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntRestFull" [[2, 3, 4, 5]] [GeneVectorInt [1, 2, 3, 4, 5], StateFunc (instructionVectorIntRest, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntRestEmpty" [[]] [GeneVectorInt [], StateFunc (instructionVectorIntRest, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntButLastFull" [[1, 2, 3, 4]] [GeneVectorInt [1, 2, 3, 4, 5], StateFunc (instructionVectorIntButLast, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntButLastEmpty" [[]] [GeneVectorInt [], StateFunc (instructionVectorIntButLast, "placeholder")] emptyState
intTestFunc "instructionVectorIntLength3" [3] [GeneVectorInt [1, 2, 3], StateFunc (instructionVectorIntLength, "placeholder")] emptyState
intTestFunc "instructionVectorIntLength0" [0] [GeneVectorInt [], StateFunc (instructionVectorIntLength, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntReverse" [[4, 3, 2, 1]] [GeneVectorInt [1, 2, 3, 4], StateFunc (instructionVectorIntReverse, "placeholder")] emptyState
intTestFunc "instructionVectorIntPushAllFull" [1, 2, 3, 4, 99] [GeneVectorInt [1, 2, 3, 4], GeneInt 99, StateFunc (instructionVectorIntPushAll, "placeholder")] emptyState
intTestFunc "instructionVectorIntPushAllEmpty" [99] [GeneVectorInt [], GeneInt 99, StateFunc (instructionVectorIntPushAll, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntMakeEmpty" [[]] [StateFunc (instructionVectorIntMakeEmpty, "placeholder")] emptyState
boolTestFunc "instructionVectorIntIsEmptyTrue" [True] [GeneVectorInt [], StateFunc (instructionVectorIntIsEmpty, "placeholder")] emptyState
boolTestFunc "instructionVectorIntIsEmptyFalse" [False] [GeneVectorInt [1, 2, 3, 4], StateFunc (instructionVectorIntIsEmpty, "placeholder")] emptyState
intTestFunc "instructionVectorIntIndexOf1" [1] [GeneVectorInt [1, 2, 3, 4, 5], GeneInt 2, StateFunc (instructionVectorIntIndexOf, "placeholder")] emptyState
intTestFunc "instructionVectorIntIndexOfFail" [-1] [GeneVectorInt [], GeneInt 2, StateFunc (instructionVectorIntIndexOf, "placeholder")] emptyState
intTestFunc "instructionVectorIntOccurrencesOf2" [2] [GeneVectorInt [1, 2, 3, 4, 2, 6, 7], GeneInt 2, StateFunc (instructionVectorIntOccurrencesOf, "placeholder")] emptyState
intTestFunc "instructionVectorIntOccurrencesOf0" [0] [GeneVectorInt [1, 2, 3, 4, 2, 6, 7], GeneInt 0, StateFunc (instructionVectorIntOccurrencesOf, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntSetNth3" [[0, 1, 2, 99, 4, 5]] [GeneVectorInt [0, 1, 2, 3, 4, 5], GeneInt 99, GeneInt 3, StateFunc (instructionVectorIntSetNth, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntSetNth9" [[0, 1, 2, 99, 4, 5]] [GeneVectorInt [0, 1, 2, 3, 4, 5], GeneInt 99, GeneInt 9, StateFunc (instructionVectorIntSetNth, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntReplace3" [[0, 1, 2, 99, 4, 5, 99, 5, 99]] [GeneInt 99, GeneInt 3, GeneVectorInt [0, 1, 2, 3, 4, 5, 3, 5, 3], StateFunc (instructionVectorIntReplace, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntReplace-1" [[0, 1, 2, 3, 4, 5, 3, 5, 3]] [GeneInt 99, GeneInt (-1), GeneVectorInt [0, 1, 2, 3, 4, 5, 3, 5, 3], StateFunc (instructionVectorIntReplace, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntReplaceFirst3" [[0, 1, 2, 99, 4, 5, 3, 5, 3]] [GeneInt 99, GeneInt 3, GeneVectorInt [0, 1, 2, 3, 4, 5, 3, 5, 3], StateFunc (instructionVectorIntReplaceFirst, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntReplaceFirst-2" [[0, 1, 2, 3, 4, 5, 3, 5, 3]] [GeneInt 99, GeneInt (-2), GeneVectorInt [0, 1, 2, 3, 4, 5, 3, 5, 3], StateFunc (instructionVectorIntReplaceFirst, "placeholder")] emptyState
vectorIntTestFunc "instructionVectorIntRemove" [[0, 1, 2, 4, 5, 5]] [GeneInt 3, GeneVectorInt [0, 1, 2, 3, 4, 5, 3, 5, 3], StateFunc (instructionVectorIntRemove, "placeholder")] emptyState
intTestFunc "instructionVectorIntIterate" [66] [GeneInt 40, GeneVectorInt [0, 1, 2, 3, 4, 5, 3, 5, 3], StateFunc (instructionVectorIntIterate, "placeholder"), StateFunc (instructionIntAdd, "placeholder")] emptyState
-- vector float functions
vectorFloatTestFunc "instructionVectorFloatConcat" [[4.0, 5.0, 6.0, 1.0, 2.0, 3.0]] [GeneVectorFloat [1.0, 2.0, 3.0], GeneVectorFloat [4.0, 5.0, 6.0], StateFunc (instructionVectorFloatConcat, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatConj" [[99.0, 1.0, 2.0, 3.0]] [GeneVectorFloat [1.0, 2.0, 3.0], GeneFloat 99.0, StateFunc (instructionVectorFloatConj, "placeholder")] emptyState
vectorFloatTestFunc "instructionFloatTakeN" [[1.0, 2.0], [6.0, 7.0, 8.0]] [GeneVectorFloat [6.0, 7.0, 8.0], GeneVectorFloat [1.0, 2.0, 3.0], GeneInt 2, StateFunc (instructionVectorFloatTakeN, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatSubVector" [[1.0, 2.0, 3.0]] [GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], GeneInt 3, GeneInt 1, StateFunc (instructionVectorFloatSubVector, "placeholder")] emptyState
floatTestFunc "instructionVectorFloatFirst" [1.0] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0, 5.0], StateFunc (instructionVectorFloatFirst, "placeholder")] emptyState
floatTestFunc "instructionVectorFloatLast" [5.0] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0, 5.0], StateFunc (instructionVectorFloatLast, "placeholder")] emptyState
floatTestFunc "instructionVectorFloatNthInBounds" [2.0] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0, 5.0], GeneInt 1, StateFunc (instructionVectorFloatNth, "placeholder")] emptyState
floatTestFunc "instructionVectorFloatNthOverflow" [2.0] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0, 5.0], GeneInt 6, StateFunc (instructionVectorFloatNth, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatRestFull" [[2.0, 3.0, 4.0, 5.0]] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0, 5.0], StateFunc (instructionVectorFloatRest, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatRestEmpty" [[]] [GeneVectorFloat [], StateFunc (instructionVectorFloatRest, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatButLastFull" [[1.0, 2.0, 3.0, 4.0]] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0, 5.0], StateFunc (instructionVectorFloatButLast, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatButLastEmpty" [[]] [GeneVectorFloat [], StateFunc (instructionVectorFloatButLast, "placeholder")] emptyState
intTestFunc "instructionVectorFloatLength3" [3] [GeneVectorFloat [1.0, 2.0, 3.0], StateFunc (instructionVectorFloatLength, "placeholder")] emptyState
intTestFunc "instructionVectorFloatLength0" [0] [GeneVectorFloat [], StateFunc (instructionVectorFloatLength, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatReverse" [[4.0, 3.0, 2.0, 1.0]] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0], StateFunc (instructionVectorFloatReverse, "placeholder")] emptyState
floatTestFunc "instructionVectorFloatPushAllFull" [1.0, 2.0, 3.0, 4.0, 99.0] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0], GeneFloat 99.0, StateFunc (instructionVectorFloatPushAll, "placeholder")] emptyState
floatTestFunc "instructionVectorFloatPushAllEmpty" [99.0] [GeneVectorFloat [], GeneFloat 99.0, StateFunc (instructionVectorFloatPushAll, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatMakeEmpty" [[]] [StateFunc (instructionVectorFloatMakeEmpty, "placeholder")] emptyState
boolTestFunc "instructionVectorFloatIsEmptyTrue" [True] [GeneVectorFloat [], StateFunc (instructionVectorFloatIsEmpty, "placeholder")] emptyState
boolTestFunc "instructionVectorFloatIsEmptyFalse" [False] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0], StateFunc (instructionVectorFloatIsEmpty, "placeholder")] emptyState
intTestFunc "instructionVectorFloatIndexOf1" [1] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0, 5.0], GeneFloat 2.0, StateFunc (instructionVectorFloatIndexOf, "placeholder")] emptyState
intTestFunc "instructionVectorFloatIndexOfFail" [-1] [GeneVectorFloat [], GeneFloat 2.0, StateFunc (instructionVectorFloatIndexOf, "placeholder")] emptyState
intTestFunc "instructionVectorFloatOccurrencesOf2" [2] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0, 2.0, 6.0, 7.0], GeneFloat 2.0, StateFunc (instructionVectorFloatOccurrencesOf, "placeholder")] emptyState
intTestFunc "instructionVectorFloatOccurrencesOf0" [0] [GeneVectorFloat [1.0, 2.0, 3.0, 4.0, 2.0, 6.0, 7.0], GeneFloat 0.0, StateFunc (instructionVectorFloatOccurrencesOf, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatSetNth3" [[0.0, 1.0, 2.0, 99.0, 4.0, 5.0]] [GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], GeneFloat 99.0, GeneInt 3, StateFunc (instructionVectorFloatSetNth, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatSetNth9" [[0.0, 1.0, 2.0, 99.0, 4.0, 5.0]] [GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0], GeneFloat 99.0, GeneInt 9, StateFunc (instructionVectorFloatSetNth, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatReplace3" [[0.0, 1.0, 2.0, 99.0, 4.0, 5.0, 99.0, 5.0, 99.0]] [GeneFloat 99.0, GeneFloat 3.0, GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 3.0, 5.0, 3.0], StateFunc (instructionVectorFloatReplace, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatReplace-1" [[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 3.0, 5.0, 3.0]] [GeneFloat 99.0, GeneFloat (-1.0), GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 3.0, 5.0, 3.0], StateFunc (instructionVectorFloatReplace, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatReplaceFirst3" [[0.0, 1.0, 2.0, 99.0, 4.0, 5.0, 3.0, 5.0, 3.0]] [GeneFloat 99.0, GeneFloat 3.0, GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 3.0, 5.0, 3.0], StateFunc (instructionVectorFloatReplaceFirst, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatReplaceFirst-2" [[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 3.0, 5.0, 3.0]] [GeneFloat 99.0, GeneFloat (-2.0), GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 3.0, 5.0, 3.0], StateFunc (instructionVectorFloatReplaceFirst, "placeholder")] emptyState
vectorFloatTestFunc "instructionVectorFloatRemove" [[0.0, 1.0, 2.0, 4.0, 5.0, 5.0]] [GeneFloat 3, GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 3.0, 5.0, 3.0], StateFunc (instructionVectorFloatRemove, "placeholder")] emptyState
floatTestFunc "instructionVectorFloatIterate" [66.0] [GeneFloat 40.0, GeneVectorFloat [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 3.0, 5.0, 3.0], StateFunc (instructionVectorFloatIterate, "placeholder"), StateFunc (instructionFloatAdd, "placeholder")] emptyState