|
| 1 | +USAGE := Usage: please input a number |
| 2 | + |
| 3 | +# Numbers are represented as x's so that they can be manipulated with text functions. |
| 4 | +# This idea is based on how the GNU Make Standard Library (https://github.com/jgrahamc/gmsl) |
| 5 | +# handles numbers. |
| 6 | +X0 := |
| 7 | +X1 := x |
| 8 | + |
| 9 | +# Constants |
| 10 | +NUMBERS := 0 1 2 3 4 5 6 7 8 9 |
| 11 | +EVEN_NUMBERS := 0 2 4 6 8 |
| 12 | + |
| 13 | +# Get rest of words in a list |
| 14 | +# Arg 1: The list |
| 15 | +# Return: List with first word removed |
| 16 | +REST = $(wordlist 2,$(words $(1)),$(1)) |
| 17 | + |
| 18 | +# Repeatedly apply a function |
| 19 | +# Arg 1: Name of function. This function must take two arguments: |
| 20 | +# - Function Arg1: Current value |
| 21 | +# - Function Arg2: New value |
| 22 | +# Arg 2: The list to repeated apply the function to |
| 23 | +# Arg 3: Initial value |
| 24 | +_REDUCE = $(if $(4),$(call _REDUCE,$(1),$(call $(1),$(2),$(3)),$(firstword $(4)),$(call REST,$(4))),$(call $(1),$(2),$(3))) |
| 25 | +REDUCE = $(call _REDUCE,$(1),$(3),$(firstword $(2)),$(call REST,$(2))) |
| 26 | + |
| 27 | +# Split number into individual digits |
| 28 | +# Arg 1: Number to split |
| 29 | +# Return: Number split into individual digits |
| 30 | +_SUBST_SPACE = $(subst $(2), $(2),$(1)) |
| 31 | +SPLIT_NUMBER = $(strip $(call REDUCE,_SUBST_SPACE,$(NUMBERS),$(1))) |
| 32 | + |
| 33 | +# Indicate if valid number |
| 34 | +# Arg 1: Number |
| 35 | +# Return: $(X1) if valid number, $(X0) otherwise |
| 36 | +IS_VALID_NUMBER = $(if $(strip $(1)),$(if $(filter-out $(NUMBERS),$(call SPLIT_NUMBER,$(1))),$(X0),$(X1)),$(X0)) |
| 37 | + |
| 38 | +# Indicate if number is even or odd |
| 39 | +# Arg 1: Number |
| 40 | +# Return: $(X1) if even, $(X0) otherwise |
| 41 | +IS_EVEN = $(if $(filter $(EVEN_NUMBERS),$(lastword $(call SPLIT_NUMBER,$(1)))),$(X1),$(X0)) |
| 42 | + |
| 43 | +# Remove leading minus sign from input value |
| 44 | +ABS_VALUE := $(patsubst -%,%,$(ARGV1)) |
| 45 | + |
| 46 | +# If invalid number, display usage statement |
| 47 | +# Else if indicate if number is even or odd |
| 48 | +ifeq (,$(call IS_VALID_NUMBER,$(ABS_VALUE))) |
| 49 | +$(info $(USAGE)) |
| 50 | +else |
| 51 | +$(info $(if $(call IS_EVEN,$(ABS_VALUE)),Even,Odd)) |
| 52 | +endif |
| 53 | + |
| 54 | +.PHONY: |
| 55 | +all: ;@: |
0 commit comments