Function 河内移动func。在哈斯克尔
我在另一篇帖子中看到了一个答案:Function 河内移动func。在哈斯克尔,function,haskell,Function,Haskell,我在另一篇帖子中看到了一个答案: type Position = Int type Move = (Position,Position) type Towers = ([Int],[Int],[Int]) hanoi 1 i j = [(i,j)] hanoi n i j = hanoi n' i otherT ++ [(i,j)] ++ hanoi n' otherT j where n' = n-1 otherT = 1+2+3-i-j -- o
type Position = Int
type Move = (Position,Position)
type Towers = ([Int],[Int],[Int])
hanoi 1 i j = [(i,j)]
hanoi n i j = hanoi n' i otherT ++ [(i,j)] ++ hanoi n' otherT j
where n' = n-1
otherT = 1+2+3-i-j -- other tower
move ::([Move],Towers) -> ([Move],Towers)
move ([],(xs,ys,zs) ) = ((error "Error"),(xs,ys,zs) )
move (((a,b): tail), (xs,ys,zs) ) | a > 3 = (tail, ((error "Error"),ys,zs) )
| b > 3 = (tail, ((error "Error"),ys,zs ) )
| otherwise = hilfsfunktion (((a,b): tail), (xs,ys,zs) )
hilfsfunktion (((1,2): tail), ((x:xs),(y:ys),zs) )
| x < y = (tail, (xs, (x:y:ys),zs) )
| x > y = (tail, (xs, (error "too big"),(error "too big")))
hilfsfunktion (((1,2): tail), ((x:xs), [],zs) ) = (tail, (xs, x:[],zs) )
但我不能让它在哈斯克尔起作用
*Main> move(it, ([1,2,3],[],[]))
*** Exception: Tu.hs:(19,1)-(22,72): Non-exhaustive patterns in function hilfsfunktion
我的问题是:
(a,b):tail
在这里是如何工作的第一件事是,你陷入了一个新手哈斯凯勒的常见错误;认为所有函数参数都应该放在括号中,如下所示:
foo (a, b, c) = ....
在大多数语言中,这将是一个三参数函数。在Haskell中,它是一个函数,接受由三元素元组组成的单个参数。你应该写信
foo a b c = ....
这避免了多余的括号,并使您在开始使用高阶函数时更加轻松
现在谈谈你问题的要点:
你的HilfFunktion定义了两种情况。在这两种情况下,参数中的第一个列表必须以元素(1,2)开头。如果您传入任何其他内容,那么它将无法匹配任何一种情况,从而导致您收到的异常消息。您实现的
hilfsfunktion
仅适用于从塔楼(我猜)1到2的移动-但还有更多!在这里你可以找到一个-也许你会发现它很有趣,帮助很大。但是我在这里尝试做的是:1,有一个move的函数:([move],Towers)->([move],Towers),它获取一个移动列表和一个游戏配置,检查第一步,然后执行。然后是2,所有移动的函数:([Move],Towers)->Towers。也许你会喜欢那里我有这样的东西(但它的大小是原来的两倍,而且不是很优雅)-你会在那里找到Move
,它会尝试这样做一个移动?xfoo a b c = ....