计算Haskell中的前缀 [英] Counting prefixes in Haskell

查看:109
本文介绍了计算Haskell中的前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在haskell中编写了2个函数,现在我必须编写第三个函数来计算haskell中的前缀数量。这里有一个例子:



我必须列出。第一个是前缀列表,另一个是文本列表。这个函数假设要做的是计算每个单词从前缀列表中出现的次数是文本列表中所有单词的前缀,并将其显示在一个元组中(单词,它显示为前缀的次数在文字中:

前缀列表[go,co]



文本列表[高尔夫,公司,计数]



这应该返回[(go,1),(co,2)]



我到目前为止是这样的:

  isPrefixOf ::(等式a) => [a]  - > [a]  - > Bool 
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf(x:xs)(y:ys )= x == y&& isPrefixOf xs ys


prefixCount ::(等式a1,数字a)=> [a1] - > [[a1]] - > a
prefixCount _ [] = 0
prefixCount x(y:ys)| isPrefixOf xy = 1 + prefixCount x ys
|否则= prefixCount x ys



howManyPrefixes _ [] = 0
howManyPrefixes [] _ = 0
howManyPrefixes(x:xs)(y:ys)=(x,pref ixCount x(y:ys))

任何帮助?

zip 这很容易

  howManyPrefixes ps ws = zip ps $ map(`prefixCount` ws)ps 



<现在,因为这看起来像作业,我会让你自己写递归解决方案,一些有用的提示。


  1. 你几乎在那里使用您当前的解决方案

  2. 不要检查第二个列表(您的计数前缀所在的列表)是否为空。这是您当前解决方案的第二个条款。
  3. 在您的最后一个条款中,通过将该元组包含在从$ $ $ c列出的
    列表中,添加递归步骤howManyPrefixes xs(y:ys)

  4. 不要在第二个列表上模式匹配,例如 y:ys 。它没关系,如果它是空的。


I've written 2 functions in haskell, and now i have to write a third one, for calculating the number of prefixes in haskell. here's an example:

i have to lists. the first is the prefixes list, and the other one is the text list. what this function is suppose to do, is to calculate the number of times each word from the prefix list is a prefix of all the words in the text list, and present it in a tuple (word, number of times it appears as a prefix in the text words:

prefix list ["go", "co"]

text list ["golf", "company", "count"]

this should return [("go", 1) , ("co", 2)]

what i have so far is this:

isPrefixOf :: (Eq a) => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xs) (y:ys) = x == y  && isPrefixOf xs ys


prefixCount :: (Eq a1, Num a) => [a1] -> [[a1]] -> a
prefixCount _ [] = 0
prefixCount x (y:ys) | isPrefixOf x y = 1 + prefixCount x ys
                 | otherwise = prefixCount x ys



howManyPrefixes _ [] = 0
howManyPrefixes [] _ = 0
howManyPrefixes (x:xs) (y:ys) = (x, prefixCount x (y:ys))

Any help?

解决方案

Using zip this is quite easy

howManyPrefixes ps ws = zip ps $ map (`prefixCount` ws) ps

Now since this looks like homework I'll let you write the recursive solution yourself, some helpful hints.

  1. You're almost there with your current solution
  2. Don't check if the second list (the one your counting prefixs in) is empty. This is the second clause of your current solution.
  3. In your last clause, add the recursive step by consing that tuple onto the resulting list from howManyPrefixes xs (y:ys)
  4. Don't pattern match on the second list, eg y:ys. It doesn't matter if it's empty.

这篇关于计算Haskell中的前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆