gpt4 book ai didi

带有元组的 Haskell 列表

转载 作者:行者123 更新时间:2023-12-02 08:09:27 25 4
gpt4 key购买 nike

subject = [("maths",[]),("science",[]),("chemistry",[]),("french",[])]

marks = [("science","john"),("maths","john"),("chemistry","ron"),("maths","ron"),("maths","sam")]

output as

[("maths",["john","ron","sam"]),("science",["john"]),("chemistry",["ron"]),("french",[])]

我的尝试:

nlist =  foldl'(\ (subjectname,studentname) (x,y) ->
if(x `elem` subjectname)
then (subjectname,studentname++[y])
else (subjectname,studentname) ) subject marks

谁能告诉我我在这里做错了什么。我收到错误:输入 nlist 解析错误

最佳答案

写出类型!这是我如何使用类型来构建程序的示例。之后,我将向您展示如何使用类型来修复您自己的程序。

type Subject = String
type Person = String

insertOne :: (Subject, Person) -> [(Subject, [Person])] -> [(Subject, [Person])]

insertMany :: [(Subject, [Person])] -> [(Subject, Person)] -> [(Subject, [Person])]

subject :: [(Subject, [Person])]

marks :: [(Subject, Person)]

nlist = insertMany subject marks

显然你已经想通了

insertMany = foldr insertOne

剩下的就是实现insertOne:

insertOne (subject, person) =
map (\(subject',list) -> if subject' == subject
then (subject', person:list)
else (subject', list))

请注意,写出类型有助于您编写正确的程序。要了解为什么您的程序无效,让我们尝试写出类型:

f :: (Subject, [Person]) -> (Subject, Person) -> (Subject, [Person])
f = (\ (subjectname,studentname) (x,y) ->
if(x `elem` subjectname)
then (subjectname,studentname++[y])
else (subjectname,studentname) )
  1. x elem subjectname 没有意义,因为 subjectname 不是 String 的列表。应该是x == subjectname,否则这个功能不错!
  2. foldl f 的类型为 (Subject, [Person]) -> [(Subject, Person)] -> [(Subject, Person)]

这个程序只能更新一个主题,例如

foldl f ("maths",[]) marks == ("maths",["john","ron","sam"])

您现在需要的是通过 map 将其应用于每个主题:

map (\x -> foldl f x marks) subject == [("maths",["john","ron","sam"]),("science",["john"]),("chemistry",["ron"]),("french",[])]

关于带有元组的 Haskell 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48536606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com