Decision tables: Difference between revisions

+J
m (→‎{{header|D}}: redo the table input format to include conditions' states)
(+J)
Line 1:
{{draft task}}
[[wp:Decision_table|Decision Tables]] are a precise yet compact way to model complicated logic. Demonstrate how your language implements decision tables. Use the example of Printer Troubleshooting given in the Wikipedia article.
 
=={{header|J}}==
Demonstrate how your language implements decision tables. Use the example of Printer Troubleshooting given in the Wikipedia article.
'''Solution''':<lang j>( , (,.~'_NAMES',L:0~]) ;:'RULES ACTIONS') =: , > split&.|:L:1 }.&.> (split~ (<'Actions:') i.&1@:= {."1) }."1 TAB makeTable noun define
Printer troubleshooter:
Printer does not print Y Y Y Y N N N N
A red light is flashing Y Y N N Y Y N N
Printer is unrecognised Y N Y N Y N Y N
Actions:
Check the power cable X
Check the printer-computer cable X X
Ensure printer software is installed X X X X
Check/replace ink X X X X
Check for paper jam X X
)
 
boxIdx =: <"1@:(<"0)
RULE_TABLE =: ACTIONS ( (<,'X') = [ )`([: boxIdx (<,'Y') = ])`(0 $~ (,~ $&2)&({:@$)) } RULES
 
troubleshoot =: verb define
RULE_TABLE troubleshoot~ RULES_NAMES ,&< ACTIONS_NAMES
:
'R A'=.x
smoutput 'Having trouble? Let''s track down the problem:'
> (,~ (<;._2'Suggested resolutions: /Solution unknown./') {~ 0=#) TAB,&.> A #~ y {~ boxIdx (<,'Y')=toupper@:(1!:1)@:1:@:smoutput@:(TAB , ,&'?')&.> R
)</lang>
 
'''Example''' (''solution found''):<lang j> troubleshoot ''
Having trouble? Let's track down the problem:
Printer does not print?
Y
A red light is flashing?
Y
Printer is unrecognised?
Y
Suggested resolutions:
Check the printer-computer cable
Ensure printer software is installed
Check/replace ink </lang>
'''Example''' (''solution not found''):<lang j> troubleshoot ''
Having trouble? Let's track down the problem:
Printer does not print?
N
A red light is flashing?
N
Printer is unrecognised?
N
Solution unknown.
)</lang>
 
=== Comments ===
The only interesting line in this solution is the one that assigns <tt>RULE_TABLE</tt>. The rest is mostly ancillary support. This is because the task highlights some freedoms J's multidimensional nature provides to the programmer.
 
Here, we create an array with as many axes (dimensions) as there are rules (questions), plus one. All axes, except the last, have 2 values (to wit: true & false). The last axis contains a boolean vector indicating which actions to try (or not). Thus, J's multidimensional array is leveraged as a tree, and the user's answers provide a path to a leaf (which is accessed arraywise, i.e. all at once).
 
For large numbers of rules and few actions, J's native support of sparse arrays might provide a performance advantage, particularly in space.
 
=={{header|D}}==
Anonymous user