将小写字母转换为大写字母 [英] Converting lowercase letters to capitals

查看:123
本文介绍了将小写字母转换为大写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Haskell的新手,并且定义了一个将所有小写字母转换为大写字母并保持其他字母不变的函数。

I am a newbie in Haskell and have some problem of defining a function that would convert all small letters to capital and leave the rest intact.

我试着解决这个问题到目前为止我的书中提到的问题:

I tried solving this question in my book so far:

capitalise :: String -> String
capitalise xs = [capitalise2 ch| ch<-xs]

capitalise2 :: Char -> Char
capitalise2 ch 
    | isLower ch    = chr (ord ch - 32)
    | otherwise    = ch

我遇到错误:

I am getting errors:

p3.hs:6:7: Not in scope: `isLower'
p3.hs:6:23: Not in scope: `chr'
p3.hs:6:28: Not in scope: `ord'

任何帮助都将不胜感激。

Any help would be much appreciated.

推荐答案

首先,您需要导入Data.Char 它是抱怨的功能。

First, you need to import Data.Char to use those functions it is complaining about.

对,你在新函数中缺少否则的情况。如果.. then .. else 构造,请使用来尝试。有经验的Haskellers不会非常使用这个构造;我可能会用辅助函数来做:

Right, you are missing the otherwise case in the new function. Try it with an if .. then .. else construct. Experienced Haskellers do not use that construct very much; I would probably do it with a helper function:

capitalize cs = [ toUpper c | c <- cs ]
    where
    toUpper ...

即几乎与你已有的一样,主要区别在于帮助函数的作用域。

which is pretty much the same as what you already have, the main difference being the scope of the helper function.

另见 Data.Char.toUpper

这也是一个很好的机会,可以免除列表解析并开始使用高阶函数。尝试使用地图而不是列表编写此功能理解。

This may also be a good opportunity to break free of list comprehensions and start to play with higher order functions. Try writing this function with map instead of a list comprehension.

这篇关于将小写字母转换为大写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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