Comparing functions in Haskell

前端 未结 5 718
情话喂你
情话喂你 2020-11-30 13:48

Is there any way to compare two functions in Haskell?

My thought is that the answer is no since functions would not derive the Eq type class. However I\'m trying to

5条回答
  •  心在旅途
    2020-11-30 14:30

    Well, there's no concept of "reference equality" in Haskell, and "behavioral equality" of functions isn't possible to check in the general case. Although it is possible to do it for functions operating only on small, finite types (as Rank would be), it's usually unwise because it leads to combinatorial explosion if you're not careful.

    There are various ways you could accomplish your immediate goal, such as:

    • Instead of using succ and pred directly, use self-guarding functions with type Enum a => a -> Maybe a that produce Nothing rather than an exception.

    • Pass in a "stop" value to check against, e.g. search op end x list = if x == end then [] ....

    • Forget about succ and pred entirely and just pass in a list of values to compare against, e.g. search :: [Rank] -> Card -> [Card] -> [Card], and end the search if the list of ranks is empty.

    A couple other remarks on your code:

    • Your list comprehension is reinventing the wheel--look for standard library functions, such as filter, that will do what you want.

    • Don't compare the length of a list to a small constant--use pattern matching instead.

提交回复
热议问题