如何使用来自getLine的字符串映射?[Haskell]

wys*_*iet 2 haskell map getline

我想读取一个String和toUpper所有的字符.

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
Run Code Online (Sandbox Code Playgroud)

然后我得到了这个

Couldn't match expected type `IO a0' with actual type `[b0]'
    In the return type of a call of `map'
    In a stmt of a 'do' expression: map toUpper a
    In the expression:
      do { a <- getLine;
           b <- getLine;
           map toUpper a;
           if (a == b) then
               print 0
           else
               if (a < b) then print (- 1) else print 1 }
Run Code Online (Sandbox Code Playgroud)

我可以使用来自getLine的String来使用map吗?或者有另一种方法来读取字符串和上述所有字符?

Ada*_*ner 7

您根本没有将map通话的"结果"分配给任何内容.这导致你得到的类型错误,这告诉你你正在尝试返回一个字符串(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
Run Code Online (Sandbox Code Playgroud)

如果您使用,fmap您可以同时使用toUpper所有字符并获得输入行(防止需要a c).

import Data.Char

main = do
    a <- fmap (map toUpper) getLine
    b <- getLine
    if a == b
        then print 0
        else if a < b
            then print (-1)
            else print 1
Run Code Online (Sandbox Code Playgroud)


Dan*_*ner 7

其他人已经以最小的方式纠正了你的程序,但我想指出Haskell已经改进的C-ism:

if (a == b)
    then print 0
    else if (a < b)
        then print (-1)
        else print 1
Run Code Online (Sandbox Code Playgroud)

是不是曾经困扰过你,数字被用于记录事物的比较?这肯定困扰着我.幸运的是,在Haskell中定义新数据类型非常便宜,我们一直都在这样做.在标准库中,有一个类型定义如下:

data Ordering = LT | EQ | GT
Run Code Online (Sandbox Code Playgroud)

还有一个标准功能

compare :: Ord a => a -> a -> Ordering
Run Code Online (Sandbox Code Playgroud)

那么为什么不使用这个美丽的Haskell工件呢?

main = do
    a <- getLine
    b <- getLine
    print (compare (map toUpper a) b)
Run Code Online (Sandbox Code Playgroud)