@@ -108,7 +108,6 @@ exprs ns = [e | (ls, rs) <- split ns,
108
108
r <- exprs rs,
109
109
e <- combine l r]
110
110
111
- -- | Combines each pair of expressions using the four numeric operators.
112
111
combine :: Expr -> Expr -> [Expr ]
113
112
combine l r = [App o l r | o <- ops]
114
113
@@ -125,3 +124,30 @@ solutions ns n =
125
124
126
125
main :: IO ()
127
126
main = print (solutions [1 ,3 ,7 ,10 ,25 ,50 ] 765 )
127
+
128
+ type Result = (Expr , Int )
129
+
130
+ -- | Returns all possible results comprising expressions whose list of values
131
+ -- is precisely a given list.
132
+ --
133
+ -- For the empty list there are no possible results.
134
+ -- For a single number there is a single result formed from that number.
135
+ -- Otherwise, for two or more numbers we first produce all splittings of the
136
+ -- list, then recursively calculate all possible results for each of these
137
+ -- lists
138
+ -- Finally, combine each of the four numeric operators that are valid.
139
+ results :: [Int ] -> [Result ]
140
+ results [] = []
141
+ results [n] = [(Val n, n) | n > 0 ]
142
+ results ns = [res | (ls, rs) <- split ns,
143
+ lx <- results ls,
144
+ ry <- results rs,
145
+ res <- combine' lx ry]
146
+
147
+ combine' :: Result -> Result -> [Result ]
148
+ combine' (l,x) (r,y) =
149
+ [(App o l r, apply o x y) | o <- ops, valid o x y]
150
+
151
+ solutions' :: [Int ] -> Int -> [Expr ]
152
+ solutions' ns n =
153
+ [e | ns' <- choices ns, (e, m) <- results ns', m == n]
0 commit comments