简体   繁体   中英

Haskell trying to mutate string in [String]

movex [] a s = []    
movex (x:xs) a s
| elem a x = moveNow x a s
| otherwise = x : (movex xs a s)
where
  moveNow x a s
    | s == 'l' = moveNow2 x a
    where
        moveNow2 [] _ = []
        moveNow2 (x:y:xs) a
          | x == ' ' && y == a = a : x : moveNow2 (y:xs) a
          | otherwise = x : moveNow2 (y:xs) a

<- This is what I got right now

I am trying to make a function that iterates through [string], finds the right string and then mutates it.

given input

func ["abc", "dfg"] f l -- move f in this list 1 space left --

expected output

["abc", "fdg"]

Right now I am stuck at movex function that gives me error

Couldn't match expected type `Char' with actual type `[Char]'
In the first argument of `(:)', namely `x'
In the expression: x : (movex xs a s)

Direct solution to the error is to replace the line

| elem a x = moveNow x a s

With

| elem a x = moveNow x a s : movex xs a s

Or, probably

| elem a x = moveNow x a s : xs

Depending on what you want to do after the first match: continue looking for certain character, or leave other strings untouched.

Your moveNow function has return type String , or [Char] , while movex has [String] , or [[Char]] , that's why compiler complains.

To avoid such problems(or fix them easier) consider writing explicit type signatures, like so:

movex :: [String]->String->String->[String]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM