我可以在Haskell的守卫中使用守卫吗?

时间:2013-10-02 21:48:15

标签: haskell guard

我在Haskell的守卫中试图使用警卫时遇到了一个问题,我试图找出是否(甚至)不可能这样做但我在互联网上找不到任何答案,我希望你伙计们可能知道答案。这是我在尝试编译代码时遇到的错误: Assignment2.hs:134:75: parse error on input '|'

我的代码:

    verticals :: Board -> (Row, Row, Row)   
    verticals ((a,b,c),(d,e,f),(g,h,i)) = ((a,d,g),(b,e,h),(c,f,i))

    symbolToPlayer :: Field -> Player   
    symbolToPlayer X = P1  
    symbolToPlayer O = P2

    showTime :: Board -> Maybe Player  
    showTime ((a,b,c),(d,e,f),(g,h,i))
                        | a==b && a==c = Just (symbolToPlayer a)          
                        | d==e && d==f = Just (symbolToPlayer d)  
                        | g==h && g==i = Just (symbolToPlayer i)
                        | otherwise = False

    hasWinner :: Board -> Maybe Player  
    hasWinner b@((a,b,c),(d,e,f),(g,h,i))       
                                   | showTime b        -> spot of error
                                   | showTime (verticals b)
                                   | a==e && a==i = Just (symbolToPlayer a)
                                   | c==e && c==g = Just (symbolToPlayer c)
                                   | otherwise = Nothing

代码是针对井字游戏的,这部分代码应该找出哪个玩家赢了;类型板是自定义的,输入的例子:hasWinner((X,O,X),(X,O,O),(X,X,O))(输出应该是:只是P1)。

感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

您的程序中至少有2个严重的语法错误和一个类型错误。

语法错误:

    | showTime b        -> spot of error
    | showTime (verticals b)

这里缺少右侧。一般形式是

    | guard = expression

如果没有表达,你就无法逃脱。编译器等待'=',但找到'|'下一个后卫,所以它知道它的错误。

类型错误在这里:

    | g==h && g==i = Just (symbolToPlayer i)
    | otherwise = False

您必须决定该函数是返回Bool还是Maybe Player

答案 1 :(得分:1)

这个怎么样?

import Control.Monad (msum)
import Control.Applicative ((<*>), pure)

data Player = P1 | P2 | None deriving (Eq, Show)

data Field = X | O | B deriving (Eq, Show)

type Board = ((Field, Field, Field)
             ,(Field, Field, Field)
             ,(Field, Field, Field))

symbolToPlayer :: Field -> Player
symbolToPlayer X = P1
symbolToPlayer O = P2
symbolToPlayer B = None

checkThree :: (Field,Field,Field) -> Maybe Player
checkThree (a,b,c)
    | a == b && a == c = Just $ symbolToPlayer a
    | otherwise        = Nothing

winHorizontal :: Board -> Maybe Player
winHorizontal (r1, r2, r3) = msum $ map checkThree [r1, r2, r3]

winVertical :: Board -> Maybe Player
winVertical ((a,b,c), (d,e,f), (g,h,i)) =
    msum $ map checkThree [(a,d,g), (b,e,h), (c,f,i)]

winDiagonal :: Board -> Maybe Player
winDiagonal ((a,_,c), (_,e,_), (g,_,i)) =
    msum $ map checkThree [(a,e,i), (c,e,g)]

hasWinner :: Board -> Maybe Player
hasWinner b = msum $ [winHorizontal, winVertical, winHorizontal] <*> pure b

Monad和Applicative是你的朋友!