chs
chs

Reputation: 652

Evaluate partially applied function

I'd like to implement an index structure as follows:

f :: [String] -> String -> Maybe Int
f haystack needle = Map.lookup needle m
  where m = Map.fromAscList $ zip (sort haystack) [1..]

g :: String -> Maybe Int
g = f ["123", "456", "789", ......]

Every time I evaluate g str, the map m needs to be newly computed.

What's an elegant way to avoid that?

I feel like I'm missing some terminology here. What's the concept I'm looking for?

Upvotes: 2

Views: 94

Answers (1)

Either use a lambda:

f :: [String] -> String -> Maybe Int
f haystack = \needle -> Map.lookup needle m
  where m = Map.fromAscList $ zip (sort haystack) [1..]

Or go pointfree:

f :: [String] -> String -> Maybe Int
f haystack = flip Map.lookup $ Map.fromAscList $ zip (sort haystack) [1..]

But for your specific function, you can do even better:

import Data.List (elemIndex, sort)

f :: [String] -> String -> Maybe Int
f haystack = fmap (+1) . flip elemIndex (sort haystack)

Upvotes: 3

Related Questions