如何在字符串中实现占位符 haskell.



如何创建一个函数来打印在缺少空格中具有占位符/变量的句子,然后通过将值插入占位符来获取用户输入并打印完整的句子。

我正在尝试打印多个缺少单词的句子(语句(,然后让用户可以选择 4 个不同单词的选择来完成句子。目标是在缺少的空格中添加变量,这些变量充当占位符,然后获取用户输入,并将值存储到缺少单词的变量中,然后打印完整的句子。我已经在"我的想法"部分中进一步解释了这一点

例如。这句话____不是_____。
选项:
1. 是,完成 2. 是,完成

3. 等 4. 等

我的想法

我正在尝试实现一些类似的事情,即为那些没有文本的空间使用占位符,然后在用户选择选项后,我可以在所述占位符中分配值。

  1. 某些打印句子
    "这句话$a不是$b"的函数。

$a$b以及我稍后可以调用的变量/占位符的位置 存储用户选择的单词。

    some函数,
  1. 它从第一个函数中获取句子并获取从另一个函数打印的选项,并将值放入占位符中以使句子完整。

我做了什么

我的实现方式是,使用用户可以选择的每个可能选项重写整个句子,然后打印与用户选择的选项匹配的句子。这并没有给我我正在寻找的功能方法,因为它更像是一种硬编码的方法,当使用多个句子时会变得乏味,然后每个句子都有 4 个选项。

我的代码

--First Version
import Data.List
import System.IO
main :: IO()
sentences = do
putStrLn "The Cat is ______ from ______ the city n"
putStrLn "Here are your options:"
putStrLn "A. big, nearby"
putStrLn "B. Nearby, in"
putStrLn "C: You, By"
putStrLn "D: By, Yourself"
option <- getChar
if (option == 'A' || option == 'a')
then putStrLn "The Cat is big from nearby the city"
else if (option == 'B' || option == 'b')
then putStrLn "The Cat is nearby from in the city"
else putStrLn "Error"
main = sentences   

我喜欢为此使用string-interpolate,因为它是异常安全的。然后你可以使用Maybe的折叠maybe来替换你的if

{-# LANGUAGE QuasiQuotes #-}
module Main where
import Control.Monad (forM_)
import Data.Char (toUpper)
import Data.List (lookup)
import Data.Maybe (maybe)
import Data.String.Interpolate ( i )
import System.IO
sentence :: (String, String) -> String
sentence (word1, word2) = [i|The Cat is #{word1} from #{word2} the city n|]
type Choice = (Char, (String, String))
choices :: [Choice]
choices = [ ('A', ("big"   , "nearby"))
, ('B', ("Nearby", "in"))
, ('C', ("You"   , "By"))
, ('D', ("By"    , "Yourself"))
]
presentChoice :: Choice -> IO ()
presentChoice (option, (word1, word2)) =
putStrLn [i|#{option}. #{word1}, #{word2}|]
sentences = do
putStrLn $ sentence ("______", "______")
putStrLn "Here are your options:"
forM_ choices presentChoice
option <- fmap toUpper getChar
putStrLn $ maybe "Error" sentence $ lookup option choices
main :: IO()
main = sentences

最新更新