如何将map与从getLine获取的字符串一起使用?[Haskell]

如何将map与从getLine获取的字符串一起使用?[Haskell],haskell,map,getline,Haskell,Map,Getline,我想读一个字符串,然后把所有的字符都读出来 import Data.Char main = do a <- getLine b <- getLine map toUpper a if (a == b) then print 0 else if (a < b) then print (-1) else print 1 导入数据.Char main=do a您根

我想读一个字符串,然后把所有的字符都读出来

import Data.Char

main = do 
    a <- getLine
    b <- getLine
    map toUpper a
    if (a == b) 
        then print 0
        else if (a < b) 
            then print (-1)
            else print 1
导入数据.Char
main=do
a您根本没有将
map
调用的“结果”分配给任何对象。这会导致您得到的类型错误,它告诉您正在尝试返回一个字符串(映射调用的结果),而实际上它需要是某个
IO
类型

直接修复看起来像这样:

import Data.Char

main = do 
    a <- getLine
    b <- getLine
    let c = map toUpper a
    if (c == b) 
        then print 0
        else if (c < b) 
            then print (-1)
            else print 1
import Data.Char

main = do 
    a <- getLine
    b <- getLine
    let c = map toUpper a
    if (a == c) 
        then print 0
        else if (a < b) 
            then print (-1)
            else print 1

记住,Haskell中的所有内容都是不可变的,因此调用
map toUpper a
实际上并不会修改
a
。如果要保存该结果,必须将其绑定到
let
子句中的变量。因此,您可能希望将代码更改为以下内容:

import Data.Char

main = do 
    a <- getLine
    b <- getLine
    let c = map toUpper a
    if (c == b) 
        then print 0
        else if (c < b) 
            then print (-1)
            else print 1
import Data.Char

main = do 
    a <- getLine
    b <- getLine
    let c = map toUpper a
    if (a == c) 
        then print 0
        else if (a < b) 
            then print (-1)
            else print 1
导入数据.Char
main=do

a其他人以最小的方式修改了您的程序,但我想指出Haskell改进的C-ism:

if (a == b)
    then print 0
    else if (a < b)
        then print (-1)
        else print 1
还有一个标准函数

compare :: Ord a => a -> a -> Ordering
那么为什么不使用这个漂亮的Haskell人工制品呢

main = do
    a <- getLine
    b <- getLine
    print (compare (map toUpper a) b)
main=do

a在Haskell中,将非一元代码与一元代码分开是一种很好的做法

一个非常小的改进是向外移动
打印

print $ if (a == c) 
    then 0
    else if (a < b) 
        then (-1)
        else 1
案例实施也是可能的:

c_compare a c = case (compare a c) of
    LT -> -1
    EQ -> 0
    GT -> 1

我本打算提到这一点,但我不确定OP是否需要0、1和-1的值。除此之外,你的版本要好得多。@NPoECOP,啊,谢谢。。。我想可能存在类似的东西,但我就是找不到。(我想我应该使用hoogle:),一个快速搜索从Enum返回
或者(相当可怕)
c\u比较一个c=fromEnum(比较一个c)-1
。让lift fx=return(fx)在getLine>=lift(map touper)
c_compare a c
    | a == c = 0
    | a < c = -1
    | otherwise = 1
c_compare a c = case (compare a c) of
    LT -> -1
    EQ -> 0
    GT -> 1