开发者

How to do this in haskell?

How can I do this in haske开发者_运维百科ll?

equal(S,S) -> true;
equal(S1, S2) -> {differ, S1, S2}.


Haskell has a perfectly serviceable (==) operator for checking equality (on types for which equality is defined) so I'm assuming you're referring to something else here besides merely testing equality.

I don't know Erlang, but given that you wrote equal(S, S) my first guess would be that you want pattern matches to express equality by reusing the variable name. Unfortunately Haskell (and ML-style in general) pattern matching is less powerful than in languages like Prolog; all the pattern can do is bind variables, not perform full unification.

It's true that there are constant value patterns like foo [1,2] = ... but that's just syntactic sugar for a binding and equality check, and it's only done for constant values, not variables.

The usual Haskell approach would probably be pattern guards, like this:

data EqualResult a b = Yep | Nope (a, b) deriving (Show, Eq)

equal :: (Eq a) => a -> a -> EqualResult a a
equal s1 s2 | s1 == s2  = Yep
            | otherwise = Nope (s1, s2)

On the off chance that you wanted some sort of reference equality instead of checking for equal values, that doesn't work because it doesn't even make sense in Haskell.

Edit: It has been pointed out to me that you may also have been asking about returning different result types. Working with types should be covered well in any introduction to Haskell, but the short version in this case is that if you need to return one of two possible types, you need a data type with one constructor for each; you then examine the result using pattern matching (in a declaration or case expression).

In this case, to make it look more like your function I've made a special-purpose type with two constructors: One indicating equality (with no further details) and one indicating inequality that holds a pair of values. You can also do it in a generic way using the built-in type Either a b, which has two constructors Left a and Right b.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜