【问题标题】:Return only the vowels in a list of strings仅返回字符串列表中的元音
【发布时间】:2021-12-25 22:21:49
【问题描述】:

我必须编写应该只返回元音的onlyVowels :: [[Char]] -> [[Char]] 函数。

例如:onlyVowels ["Return", "Only", "Vowels", "Please"] == ["eu", "Oy", "oe", "eae"]

到目前为止,我想出了这个:

onlyVowels x = filter (isAVowel x) x where
  isAVowel x = elem x "aeiouyAEIOUY"

问题在于我必须检查单词列表,而不仅仅是字符。此练习还禁止使用递归。

【问题讨论】:

  • 你知道map了吗?
  • 提示:先写onlyV :: [Char] -> [Char],对单个字符串进行操作。一旦你解决了这个问题,你就可以考虑如何将它扩展到字符串列表。
  • 目前最大的挑战是确定哪些字符是“元音”。这在英语中已经够棘手了(“y”是元音吗?),但是当您考虑其他语言时,它变得更加困难。而且由于几种语言可以使用相同的字符,我认为这是不可能的。

标签: list haskell filter


【解决方案1】:
onlyVowels :: [[Char]] -> [[Char]]
onlyVowels = map (filter isAVowel) where
  isAVowel x = x `elem` "aeiouyAEIOUY"

使用map 将您的过滤功能应用于字符串列表中的每个字符串。另请注意,这是 eta 减少的。和写法一样:

onlyVowels xs = map (filter isAVowel) xs where...

使用Data.Char 中的toLower 也可能是个好主意。然后你可以只过滤“aeiouy”,如下所示:

import Data.Char (toLower)

onlyVowels :: [[Char]] -> [[Char]]
onlyVowels = map (filter isAVowel) where
  isAVowel x = toLower x `elem` "aeiouy"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-13
    • 2017-01-18
    • 1970-01-01
    • 2020-06-17
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多