I wrote the code to get the element index
elemIndex :: [String] -> [String] -> [Int]
elemIndex [] [] = []
elemIndex x y = elemIndex True [(elem a y) | a <- x ]
is there any alternative way/similer of performing the above logic?
and also i’ve seen that some use
index [] _ = []
to return null lists
could you pls explain the use of underscore?
//edit 1
it is suposed to return the index of the values in the list.
eg: elemIndex [“asde”,”zxc”,”qwe”] [“qwe”,”zxc”]
returns [1,2] as the answer
thanks
elemIndextakes two arguments (two lists). Right now you recursively call it with an additional argument of type bool (namelyTrue). That will not work. What you probably want to do, is create a helper function, as I showed you an hour ago.The
_, as used as a formal argument, matches any input. It does not have a name, and as such, you cannot use that which is matched.Aside from that, you probably don’t want to use booleans, but integers (to keep track of a counter). The
elemfunction only tells you whether some value is part of a list, not where it is. So, it is of little use to you. Since this appears to be homework I will not provide a solution to your problem, but perhaps you should split your code in two:(
getIndexmay use a helper functiongetIndex' :: (Eq t) => [t] -> t -> Integer -> Integer.)Edit: One possible solution (which uses a hack, it’s nicer to use the
Maybemonad):A version with the
Maybemonad:And a version that leaves all heavy lifting to the standard library: