Haskell中递归函数的实现

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

目前,我正在学习haskell,我在逻辑上遇到麻烦,尤其是如何执行某些动作。

我想做什么

  1. 主要目标是拥有一个包含多个缺少单词的句子(语句)的功能,但是,它一次只需要打印一个句子。
  2. 我们还需要另一个函数,该函数可以打印出4个选项,这些选项将为第一个函数包含/打印的每个语句填写完整的句子(然后用户选择这些选项来填写句子)。例如。 -“此___包含____”选项:
    1. 字符串,单词
    2. 列表,选项
  3. 现在,我们需要另一个功能,该功能将从功能1提取每个句子,并从用户从功能2中选择选项,并创建一个完整的句子并将其返回给用户。

我不确定我们是否需要一个单独的函数来接受用户输入并存储他们从函数2中选择的值以完成函数1中的句子,或者是否也可以在函数2中添加它。

我能够创建的内容

我能够执行上述操作,但是我只能用一个句子执行此操作,并且所有操作都在一个函数中(在我看来,这不能使代码高效且可重用)。我再次尝试了我所想到的结构(如上所示),但是由于我的逻辑和不确定如何去做而陷入困境。下面有两个代码版本,第一个版本展示了我的目标,但是我只能用一个句子来完成它,第二个版本现在是我尝试使用多个代码的地方功能,但是我不确定下一步要去哪里。

这是第一个版本的代码

--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    

这是第二个版本的代码(我在哪里)

import Data.List
import System.IO
main :: IO()

--This function contains all the sentences 
sentences = do
    putStrLn "\nThe Cat is ______ from the ______  \n"
    putStrLn "\nThe Cow belongs to ______ from ______ ______ \n"
    putStrLn "\nThe Man lives in ______ and is neighbours with ______ \n"

-- This function basically prints after each sentence is displayed to signal to the user that they need to select an option
optionsText = do
    putStrLn "Here are your options: \n"

-- These Functions contain the different options for different sentences
options1 = do
    putStrLn "A. Running, dog"
    putStrLn "B. Hiding, Man"
    putStrLn "C. Eating, Trash"
    putStrLn "D. Calling, Roof"

options2 = do
    putStrLn "A. Tom, Next, Door"
    putStrLn "B. Rick, My, Neighbour"
    putStrLn "C. Man, farm, place"
    putStrLn "D. Sheltor, Animal, Factory"

option3 = do
    putStrLn "A. Australia, Me"
    putStrLn "B. UK, Actor"
    putStrLn "C. Florida, Tom"
    putStrLn "D. House, Dog"

目前,我正在学习haskell,我在逻辑上遇到麻烦,尤其是如何执行某些动作。我正在尝试做的主要目标是要具有一个......>

haskell recursive-datastructures
1个回答
0
投票

这似乎是关于数据建模的问题。到目前为止,您的解决方案在字符级别上起作用:您定义字符串,其中特定字符_用作占位符,并且要在此位置插入其他字符。

编程是关于抽象的。因此,退后一步,而不是根据单个字符来思考问题,而是根据句子片段

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