Haskell boshlang'ich: Data decl. xatolar

Salom Haskellda juda oddiy vazifani yozishga harakat qilaman. Biroq kodni qabul qilish uchun "ghci" ni qabul qila olmayman.

data Field = A1 Int deriving (Show)

data FieldList = FL [Field] | Name String deriving (Show)

t :: Field

t = A1 1

u :: Int -> FieldList

u 0 = FL []

u n = FL [t]:(u (n-1))

Va men olgan xato:

test.hs:9:7:

Couldn't match expected type `FieldList' with actual type `[a0]'

    In the expression: (FL [t]) : (u (n - 1))
    In an equation for `u': u n = (FL [t]) : (u (n - 1))

Kimdir meni to'g'ri yo'nalishga ko'rsatishi mumkinmi?

Rahmat!

0

3 javoblar

Oxirgi satrga qarab:

u n = FL [t]:(u (n-1))

u has the type Int -> FieldList. n is an Int, so (n - 1) is also an Int. u (n-1) would therefor be a FieldList.

Funktsiya ilovasi operatorlardan ko'ra ustunlikka ega, shuning uchun yuqoridagi satr quyidagilarga mos keladi:

u n = (FL [t]) : (u (n - 1) )

FL [t] is a FieldList.

However, (:) has the type a -> [a] -> [a]. You can see the types don't match, so that is what is causing the problem.


Field s ( [Field] ga ega) ro'yxatini tuzib, so'ng FieldList . Mana, biroz burilish kodi:

u :: Int -> FieldList
u n = FL (uHelper n)

uHelper :: Int -> [Field]
uHelper = ... -- write this function
2
qo'shib qo'ydi
Yep. Bu mening niyatim. Ularning yordami uchun barchaga rahmat!
qo'shib qo'ydi muallif dirtdog, manba

Xato, (FL [t]): (u (n - 1)) FL [T] - bu ro'yxat emas, shuning uchun u bilan cons] bo'lolmaysiz.

Menimcha, FieldList-ga FIRE yoki OR formati (ya'ni Name constructor yordamida yaratilgan) bo'lishi uchun yangi kod sifatida FieldList yaratganingizdan ishonch hosil emasman mantiqiy ma'noga ega bo'lish.

Siz nima qila olasiz:

turi FieldList = [Field]

Va keyin sizning vazifangiz shunday bo'ladi:

u :: Int -> FieldList
u 0 = []
u n = t : (u (n-1))
1
qo'shib qo'ydi

Kodingiz bilan bog'liq ikkita muammo mavjud:

  1. The first argument of list cons (:) is an element, not a list, thus: t : ... not [t] : ...
  2. You must unwrap the FieldList first to get [Field]. Then you can prepend t to it.

Sizning so'nggi chiziqingiz bo'lishini xohlaysiz

u n = case u (n-1) of FL xx -> FL (t:xx)

Bu, albatta, maydon kodi Name bo'lsa, u holda Ankur bilan dizayndagi muammo bo'lishi mumkinligiga rozilik bildirsangiz ...

0
qo'shib qo'ydi