Haskell 中的全语法检查器

问题描述 投票:0回答:1

我想知道如何检查字符串是否是pangram,作为初学者的练习。我有两个解决方案,但我根本不明白。

版本1

import Data.Char (toLower)

isPangram :: String -> Bool
isPangram str = all (`elem` map toLower str) ['a'..'z']

版本2

import Data.Char (toLower)

isPangram :: String -> Bool
isPangram str = allPresent (map toLower str) ['a'..'z']

allPresent :: String -> String -> Bool
allPresent _ [] = True
allPresent [] _ = False
allPresent (x:xs) ys
    | x `elem` ys = allPresent xs ys
    | otherwise = False

不确定它们是否正确,但任何简化或修改此问题的帮助将不胜感激!

function haskell
1个回答
0
投票

你的第二个版本不是。应该是:

isPangram :: String -> Bool
isPangram str = allPresent ['a' .. 'z'] (map toLower str)

allPresent :: String -> String -> Bool
allPresent [] _ = True
allPresent _ [] = False
allPresent (x : xs) ys
  | x `elem` ys = allPresent xs ys
  | otherwise = False

确实,对于 pangram,您检查是否所有字符都属于该字符串。但这是不对称的:检查X的所有元素是否属于Y并不等同于检查Y的所有元素是否属于X。因此,我们在这里使用第一个列表作为项目集合,我们检查该集合的每个项目

x
是否是第二个集合
ys
的元素。

© www.soinside.com 2019 - 2024. All rights reserved.