第一:我的英语不是很好,我很抱歉:(
所以,这是我必须解决的问题:
-- Based on a simple math game: given a list of numbers use the four basic
-- operations (+, -, /, *) between them to find (or be as close as possible to)
-- another given number
有我的问题的例子,但我需要更具体地解决,我无法在“haskell 模式”下思考,我是 C++ 玩家:(
所以,我已经完成了:
-- Find all possible 2-combinations of the elements of xs.
pairs :: [Int] -> [(Int, Int)]
pairs xs = [(x, y) | (x:ys) <- tails xs, y <- ys]
operations :: (Int, Int) -> [(Int, Int, Char, Int)]
operations (x, y) =
[ (x, y, '+', x + y) ] ++
[ (x, y, '*', x * y) ] ++
[ (x, y, '-', x - y) | x > y ] ++
[ (x, y, '/', x `div` y) | x >= y, x `mod` y == 0]
我必须实现另一个函数('solve')来执行以下操作:
'solve' 函数返回一个包含所有结果节点的列表,以从可用数字列表中选择一对数字,并将可能的操作应用于所选伙伴。
我将不得不更新可用号码列表(删除那些使用并添加新号码)和操作列表(以反映最新操作)
例子:
solve ( 100 , [1,4,5] , [] )
[ ( 100 , [5,5] , [(1,4,'+',5)] ), -- take first tuple 1,4 add and subs into "new tuple"5,5
( 100 , [3,5] , [(4,1,'-',3)] ),
( 100 , [6,4] , [(1,5,'+',6)] ),
( 100 , [4,4] , [(5,1,'-',4)] ),
( 100 , [9,1] , [(4,5,'+',9)] ),
( 100 , [1,1] , [(5,4,'-',1)] ),
( 100 , [20,1] , [(4,5,'*',20)] ) ]
首先取几个数字(使用pairs函数),
'操作'可以做的第二个显示[number,number,'operation',result]
。
我有这样的事情:
solve(n,ns) = [ e | ns' <- pairs ns
, e <- operations ns']
但我不能让它工作,知道吗?
编辑:
我非常感谢您的回答,非常感谢您,但是如果我不能执行我要求的功能,我将无法理解您的发展,因为我在 Haskell 中真的很新:(
正如我所说,我需要一个带有数字列表的函数以及我在主帖中编写的 2 个操作(操作和对)创建另一个函数来执行此操作:
例子)
solve ( 100 , [1,4,5] , [] )
[ ( 100 , [5,5] , [(1,4,'+',5)] ),
( 100 , [3,5] , [(4,1,'-',3)] ),
( 100 , [6,4] , [(1,5,'+',6)] ),
( 100 , [4,4] , [(5,1,'-',4)] ),
( 100 , [9,1] , [(4,5,'+',9)] ),
( 100 , [1,1] , [(5,4,'-',1)] ),
( 100 , [20,1] , [(4,5,'*',20)] ) ]
非常感谢您的快速回答,但我的回答需要更具体。