“没什么”设置的守卫

时间:2013-12-09 00:36:24

标签: haskell

更新:

公平地说,我的例子是我所面临的问题的简化,我已经尝试过实施解决方案,但它似乎没有用......

followConnection :: Connection->Crib->Stecker->Offsets->Maybe Stecker
followConnection w x y z
| steckerAdd ((enigmaEncode (getSndTripleEl w) (SimpleEnigma rotor1 rotor2 rotor3 reflectorB) (calculateOffset z (getFirstTripleEl w))), (getThirdTripleEl w)) y == Nothing = Nothing
| steckerAdd ((enigmaEncode (getSndTripleEl w) (SimpleEnigma rotor1 rotor2 rotor3 reflectorB) (calculateOffset z (getFirstTripleEl w))), (getThirdTripleEl w)) y == Just (y) = y

使用

 steckerAdd ((enigmaEncode (getSndTripleEl w) (SimpleEnigma rotor1 rotor2 rotor3 reflectorB) (calculateOffset z (getFirstTripleEl w))), (getThirdTripleEl w)) y == Just (y) = y

给予

无法匹配类型[(Char, Char)]' with或许Stecker'  预期类型:也许Stecker    实际类型:Stecker

我有一个函数(myFunction),它返回“Maybe Int”作为输出

我想编写类似于:

的代码
myOtherFunction :: Int -> Maybe Int
myOtherFunction x
| myFunction x == Nothing = 1
| myFunction x == 1 = 2
| otherwise = 3

然而,Haskell似乎并不喜欢我将“Maybe Int”值与int ...

进行比较

我还尝试通过制作它来“铸造”它:

| fromMaybe(myFunction) x == 1 = 2

功能如下:

fromMaybe :: Maybe a -> a
fromMaybe (Just x)=x

想法?

4 个答案:

答案 0 :(得分:5)

我将假设您的myFunction具有此类型:

myFunction :: Int -> Maybe Int

我也会假设您错误地写了myOtherFunction类型,因为它会产生Int结果而不是Maybe Int

myOtherFunction :: Int -> Int

执行此操作的方式是使用case语句编写的模式匹配:

myOtherFunction x = case (myFunction x) of
    Nothing -> 1
    Just 1  -> 2
    _       -> 3

答案 1 :(得分:1)

你应该使用的是模式匹配:

myOtherFunction :: Maybe Int -> Int
myOtherFunction Nothing = 1
myOtherFunction (Just 1) = 2
myOtherFunction _ = 3

您的工作不起作用的原因是您无法将Int直接与Maybe Int进行比较。在任何语言中都是如此,而不仅仅是Haskell。比较两种不同类型通常不起作用。


如果你真的想使用警卫,你可以做

myOtherFunction :: Int -> Maybe Int
myOtherFunction x
    | myFunction x == Nothing = 1
    | myFunction x == Just 1 = 2
    | otherwise = 3

答案 2 :(得分:0)

您可以这样做:

myOtherFunction :: Int -> Maybe Int
myOtherFunction x
 | myFunction x == Nothing = 1
 | myFunction x == Just 1 = 2
 | otherwise = 3

Here's an Ideone of this kind of thing.

答案 3 :(得分:0)

更新后的示例的第4行以= y结尾。但从followConnection的类型签名中可以清楚地看出,yStecker,而不是Maybe Steker

尝试将第4行的结尾更改为= Just y。这很可能是错误引用的内容,因为它希望返回Maybe Stecker,但它会获得Stecker