开发者

Haskell: Best way to turn a list of tuples into a haskell function?

i have a list of triples of strings like this:

mylist = [("a1","a2","a3"), ("b1","b2","b3"), ("c1","c2","c3")]

The actual strings are arbitrary, except that the list represents a binary function that maps the first two strings to the third. What is a computationally fast way to implement a function

f :: String -> String -> String

so that

f "a1" "a2" == "a3"
f "b1" "b2" == "b3"
f "c1" "c2" == "c3"

And also, is there a general way to do this with a list of tupl开发者_Go百科es?

So far, i only came up with

f a b = lookUp (a,b) [ ((x,y),z) | (x,y,z) <- mylist ]

Thanks, André


This is usually done with a map (see Data.Map, that link also explains how it works and how to build your own map).

You'll likely need to use a ([Char],[Char]) as key, so your data could be represented this way:

[(("a1","a2"),"a3"), (("b1","b2"),"b3"), (("c1","c2"),"c3")]


It's a bit unclear what you want this function to do. If it is an arbitrary mapping of two inputs to one output, then go with peoro's suggestion of using Data.Map. If the computation has some systematic meaning, then try to discover the algorithm behind it.

import Data.Char
incStr [c,x] | isNumber x = [c, intToDigit (digitToInt x + 1)]

ghci> incStr "a1"
"a2"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜