如何在F#中使用这种字典,而不是在集合库中使用字典 [英] how to use this kind of dictionary in F# instead of dictionary in collection library
问题描述
http://stackoverflow.com/questions/9552752/haskell-lookup-key-in-a-user-defined-dictionary
http://stackoverflow.com/questions/9552752/haskell-lookup-key-in-a-user-defined-dictionary
lookup1 :: Book -> String -> Maybe Answer
lookup1 [] key = Nothing
lookup1 ((k,v):xs) key = if key == k
then Just v
else lookup1 xs key
临近编程时代
推荐答案
oooooxxxxx,
Hi oooooxxxxx,
如果我正确理解Haskell代码,则Book是一个元组列表(字符串,字符),其中字符串是要进行比较的键,并且该函数返回该元组的字符,其中该字符串与钥匙.因此Book是用户定义的 stackoverflow示例中的字典.
If I understand the Haskell code correctly, Book is a list of tuples (string, char), where string is the key, which is about to be compared and the function returns the char of the tuple where the string matches the key. Thus Book is the user defined dictionary from the stackoverflow example.
如果是这样,请尝试以下操作:
If so, try this:
let rec lookup book key =
match book with
| ((k,v) & head) :: tail when k = key -> v
| head :: tail -> lookup tail key
| [] -> printfn "%s" "No entry with the given key was found"; ' '
我已经用以下列表对此进行了测试:
I have tested this with the following list:
let list = [("cH",'H'); ("bS", 'T'); ("jG", 'G')]
let result = lookup list "bS"
printfn "%A" result
如果我没记错的话,这与F#中的上述Haskell代码相对应.
If I am not mistaken, this is the counterpart of the above Haskell code in F#.
此致,
Dimitar
Regards,
Dimitar
这篇关于如何在F#中使用这种字典,而不是在集合库中使用字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!