Comparing functions in Haskell -
is there way compare 2 functions in haskell?
my thought answer no since functions not derive eq type class. i'm trying write pretty trivial function , seems normal sort of thing do:
search :: ((enum a) => -> a) -> card -> [card] search op x list = if (op == succ && rank x == king) || (op == pred && rank x == ace) [] else let c = [ n | n <- list, rank n == op (rank x)] in if length c == 1 x : search op (head c) list else []
error message:
no instance (eq (rank -> rank)) arising use of `=='
basically either searches or down list of cards looking match either next or previous ranked card x, building list. taking 'pred' or 'succ' function operator works both forwards , backwards. however, need check doesn't go out of bounds on enum otherwise throws exception.
so i'm looking way prevent exception or solve problem!
any other pointers on improving code appreciated :)
thanks great tips, solution have come (taken bits every answer really!):
edit: correct solution below:
maybesucc x | x == maxbound = nothing | otherwise = (succ x) maybepred x | x == minbound = nothing | otherwise = (pred x) -- takes list of cards have rank 1 op x -- if there 1 sequential, otherwise end matching search :: (rank -> maybe rank) -> rank -> [card] -> [card] search op x list = case filter (\n -> (rank n) == op x) list of [y] -> y : search op (rank y) list _ -> []
test:
*main> let cards = [card ace heart, card 2 club, card 3 spade, card 5 club, card 4 diamond] *main> search maybesucc 2 cards [three of spades,four of diamonds,five of clubs] *main> search maybepred 3 cards [two of clubs,ace of hearts]
1) op
overly general. you'll using card whatever type rank (undefined :: card)
is, make rankthing -> rankthing
. also, function type signature missing return value type.
2) example intended use looks search succ ace xs
, that's rather clumsy, how 2 auxillary functions handle bounds:
searchup king _ = [] searchup x ys = search succ x ys searchdown ace _ = [] searchdown x ys = search pred x ys
this might read better users , avoid need check operation
3) if want check operation performed, , know operation 1 of 2 possibilities, can either name operation or test known answer test (kat). example:
data operation = succ | pred search :: operation -> card -> [card] -> [] search succ king _ = [] search succ x ys = search' succ x ys search pred ace _ = [] search pred x ys = search' pred x ys
and kat solution (rather lame, imo):
search op x ys | op 5 == 4 && rank x == ace = [] | op 5 == 6 && rank x == king = [] | otherwise = ...
Comments
Post a Comment